Part Number Hot Search : 
MSKW3035 31742 GT23MABE C1210 ICX41 ER100 55C56 10E471
Product Description
Full Text Search
 

To Download ATMEGA323-8PC Datasheet File

  If you can't view the Datasheet, Please click here to try to view without PDF Reader .  
 
 


  Datasheet File OCR Text:
 Features
* High-performance, Low-power AVR(R) 8-bit Microcontroller * Advanced RISC Architecture
- 130 Powerful Instructions - Most Single-clock Cycle Execution - 32 x 8 General Purpose Working Registers - Fully Static Operation - Up to 8 MIPS Throughput at 8 MHz - On-chip 2-cycle Multiplier Non-volatile Program and Data Memories - 32K Bytes of In-System Self-programmable Flash Endurance: 1,000 Write/Erase Cycles - Optional Boot Code Section with Independent Lock Bits In-System Programming by On-chip Boot Program - 1K Byte EEPROM Endurance: 100,000 Write/Erase Cycles - 2K Bytes Internal SRAM - Programming Lock for Software Security JTAG (IEEE Std. 1149.1 Compliant) Interface - Extensive On-chip Debug Support - Programming of Flash, EEPROM, Fuses, and Lock Bits through the JTAG Interface - Boundary-Scan Capabilities According to the JTAG Standard Peripheral Features - Two 8-bit Timer/Counters with Separate Prescaler and Compare Mode - One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and Capture Mode - Real Time Counter with Separate Oscillator - Four PWM Channels - 8-channel, 10-bit ADC - Byte-oriented Two-wire Serial Interface - Programmable Serial USART - Master/Slave SPI Serial Interface - Programmable Watchdog Timer with Separate On-chip Oscillator - On-chip Analog Comparator Special Microcontroller Features - Power-on Reset and Programmable Brown-out Detection - Internal Calibrated RC Oscillator - External and Internal Interrupt Sources - Six Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down, Standby and Extended Standby I/O and Packages - 32 Programmable I/O Lines - 40-pin PDIP and 44-lead TQFP Operating Voltages - 2.7 - 5.5V (ATmega323L) - 4.0 - 5.5V (ATmega323) Speed Grades - 0 - 4 MHz (ATmega323L) - 0 - 8 MHz (ATmega323)
*
*
*
8-bit Microcontroller with 32K Bytes of In-System Programmable Flash ATmega323 ATmega323L
Not recommended for new designs. Use ATmega32.
*
* * *
1457G-AVR-09/03
Pin Configurations
PDIP
(XCK/T0) PB0 (T1) PB1 (INT2/AIN0) PB2 (OC0/AIN1) PB3 (SS) PB4 (MOSI) PB5 (MISO) PB6 (SCK) PB7 RESET VCC GND XTAL2 XTAL1 (RXD) PD0 (TXD) PD1 (INT0) PD2 (INT1) PD3 (OC1B) PD4 (OC1A) PD5 (ICP) PD6 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 PA0 (ADC0) PA1 (ADC1) PA2 (ADC2) PA3 (ADC3) PA4 (ADC4) PA5 (ADC5) PA6 (ADC6) PA7 (ADC7) AREF AGND AVCC PC7 (TOSC2) PC6 (TOSC1) PC5 (TDI) PC4 (TDO) PC3 (TMS) PC2 (TCK) PC1 (SDA) PC0 (SCL) PD7 (OC2)
TQFP
PB4 (SS) PB3 (AIN1/OC0) PB2 ((AIN0/INT2) PB1 (T1) PB0 (XCK/T0) GND VCC PA0 (ADC0) PA1 (ADC1) PA2 (ADC2) PA3 (ADC3) 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 12 13 14 15 16 17 18 19 20 21 22
(MOSI) PB5 (MISO) PB6 (SCK) PB7 RESET VCC GND XTAL2 XTAL1 (RXD) PD0 (TXD) PD1 (INT0) PD2
1 2 3 4 5 6 7 8 9 10 11
PA4 (ADC4) PA5 (ADC5) PA6 (ADC6) PA7 (ADC7) AREF AGND AVCC PC7 (TOSC2) PC6 (TOSC1) PC5 (TDI) PC4 (TDO)
2
ATmega323(L)
1457G-AVR-09/03
(INT1) PD3 (OC1B) PD4 (OC1A) PD5 (ICP) PD6 (OC2) PD7 VCC GND (SCL) PC0 (SDA) PC1 (TCK) PC2 (TMS) PC3
ATmega323(L)
Overview
The ATmega323 is a low-power CMOS 8-bit microcontroller based on the AVR enhanced RISC architecture. By executing powerful instructions in a single clock cycle, the ATmega323 achieves throughputs approaching 1 MIPS per MHz allowing the system designer to optimize power consumption versus processing speed. Figure 1. Block Diagram
PA0 - PA7 PC0 - PC7
Block Diagram
VCC
PORTA DRIVERS
PORTC DRIVERS
GND DATA REGISTER PORTA DATA DIR. REG. PORTA DATA REGISTER PORTC DATA DIR. REG. PORTC
8-BIT DATA BUS
AVCC JTAG INTERFACE 2-WIRE SERIAL INTERFACE
ANALOG MUX
AGND AREF
ADC
OSCILLATOR
XTAL1
INTERNAL REFERENCE
INTERNAL OSCILLATOR
OSCILLATOR
PROGRAM COUNTER
STACK POINTER
WATCHDOG TIMER
TIMING AND CONTROL
XTAL2 RESET
PROGRAM FLASH
SRAM
MCU CONTROL REGISTER
INSTRUCTION REGISTER
GENERAL PURPOSE REGISTERS
X Y Z
TIMER/ COUNTERS
INSTRUCTION DECODER
INTERRUPT UNIT
CONTROL LINES
ALU
EEPROM
STATUS REGISTER
INTERNAL CALIBRATED OSCILLATOR
PROGRAMMING LOGIC
SPI
USART
ANALOG COMPARATOR
DATA REGISTER PORTB
DATA DIR. REG. PORTB
DATA REGISTER PORTD
DATA DIR. REG. PORTD
+ -
PORTB DRIVERS
PORTD DRIVERS
PB0 - PB7
PD0 - PD7
3
1457G-AVR-09/03
The AVR core combines a rich instruction set with 32 general purpose working registers. All the 32 registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two independent registers to be accessed in one single instruction executed in one clock cycle. The resulting architecture is more code efficient while achieving throughputs up to ten times faster than conventional CISC microcontrollers. The ATmega323 provides the following features: 32K bytes of In-System Programmable Flash, 1K bytes EEPROM, 2K bytes SRAM, 32 general purpose I/O lines, 32 general purpose working registers, a JTAG interface for Boundary-Scan, On-chip Debugging support and programming, three flexible Timer/Counters with compare modes, internal and external interrupts, a serial programmable USART, a byte oriented Two-wire Serial Interface, an 8-channel, 10-bit ADC, a programmable Watchdog Timer with internal Oscillator, an SPI serial port, and six software selectable power saving modes. The Idle mode stops the CPU while allowing the SRAM, Timer/Counters, SPI port, and interrupt system to continue functioning. The Power-down mode saves the register contents but freezes the Oscillator, disabling all other chip functions until the next interrupt or Hardware Reset. In Power-save mode, the asynchronous timer continues to run, allowing the user to maintain a timer base while the rest of the device is sleeping. The ADC Noise Reduction mode stops the CPU and all I/O modules except asynchronous timer and ADC, to minimize switching noise during ADC conversions. In Standby mode, the crystal/resonator Oscillator is running while the rest of the device is sleeping. This allows very fast start-up combined with low-power consumption. In Extended Standby mode, both the main Oscillator and the asynchronous timer continue to run. The device is manufactured using Atmel's high-density non-volatile memory technology. The On-chip ISP Flash allows the Program memory to be re-programmed In-System through an SPI serial interface, by a conventional non-volatile memory programmer, or by an On-chip Boot Program running on the AVR core. The Boot Program can use any interface to download the application program in the Application Flash memory. By combining an 8-bit RISC CPU with In-System Programmable Flash on a monolithic chip, the Atmel ATmega323 is a powerful microcontroller that provides a highly flexible and cost effective solution to many embedded control applications. The ATmega323 AVR is supported with a full suite of program and system development tools including: C compilers, macro assemblers, program debugger/simulators, In-Circuit Emulators, and evaluation kits.
Pin Descriptions
VCC GND Port A (PA7..PA0) Digital supply voltage. Digital ground. Port A serves as the analog inputs to the A/D Converter. Port A also serves as an 8-bit bi-directional I/O port, if the A/D Converter is not used. Port pins can provide internal pull-up resistors (selected for each bit). The Port A output buffers can sink 20 mA and can drive LED displays directly. When pins PA0 to PA7 are used as inputs and are externally pulled low, they will source current if the internal pullup resistors are activated. The Port A pins are tri-stated when a reset condition becomes active, even if the clock is not running.
4
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Port B (PB7..PB0) Port B is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port B output buffers can sink 20 mA. As inputs, Port B pins that are externally pulled low will source current if the pull-up resistors are activated. The Port B pins are tri-stated when a reset condition becomes active, even if the clock is not running. Port B also serves the functions of various special features of the ATmega323 as listed on page 139. Port C (PC7..PC0) Port C is an 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port C output buffers can sink 20 mA. As inputs, Port C pins that are externally pulled low will source current if the pull-up resistors are activated. The Port C pins are tri-stated when a reset condition becomes active, even if the clock is not running. Port C also serves the functions of the JTAG interface and other special features of the ATmega323 as listed on page 146. If the JTAG interface is enabled, the pull-up resistors on pins PC5 (TDI), PC3 (TMS) and PC2 (TCK) will be activated even if a Reset occurs. Port D (PD7..PD0) Port D is an 8-bit bidirectional I/O port with internal pull-up resistors (selected for each bit). The Port D output buffers can sink 20 mA. As inputs, Port D pins that are externally pulled low will source current if the pull-up resistors are activated. The Port D pins are tri-stated when a reset condition becomes active, even if the clock is not running. Port D also serves the functions of various special features of the ATmega323 as listed on page 151. RESET Reset input. A low level on this pin for more than 500 ns will generate a Reset, even if the clock is not running. Shorter pulses are not guaranteed to generate a Reset. Input to the inverting Oscillator amplifier and input to the internal clock operating circuit. Output from the inverting Oscillator amplifier. AVCC is the supply voltage pin for Port A and the A/D Converter. It should be externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter. See page 127 for details on operation of the ADC. AREF is the analog reference pin for the A/D Converter. For ADC operations, a voltage in the range 2.56V to AVCC can be applied to this pin. Analog ground. If the board has a separate analog ground plane, this pin should be connected to this ground plane. Otherwise, connect to GND.
XTAL1 XTAL2 AVCC
AREF
AGND
5
1457G-AVR-09/03
Clock Options
The device has the following clock source options, selectable by Flash Fuse bits as shown: Table 1. Device Clocking Options Select(1)
Device Clocking Option External Crystal/Ceramic Resonator External Low-frequency Crystal External RC Oscillator Internal RC Oscillator External Clock Note: 1. "1" means unprogrammed, "0" means programmed. CKSEL3..0 1111 - 1010 1001 - 1000 0111 - 0101 0100 - 0010 0001 - 0000
The various choices for each clocking option give different start-up times as shown in Table 6 on page 27.
Internal RC Oscillator
The internal RC Oscillator option is an On-chip Oscillator running at a fixed frequency of nominally 1 MHz. If selected, the device can operate with no external components. See "Calibrated Internal RC Oscillator" on page 41 for information on calibrating this Oscillator. XTAL1 and XTAL2 are input and output, respectively, of an inverting amplifier which can be configured for use as an On-chip Oscillator, as shown in Figure 2. Either a quartz crystal or a ceramic resonator may be used. Figure 2. Oscillator Connections
Crystal Oscillator
C2 C1
XTAL2 XTAL1 GND
6
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
External Clock
To drive the device from an external clock source, XTAL1 should be driven as shown in Figure 3. Figure 3. External Clock Drive Configuration
External RC Oscillator
For timing insensitive applications, the external RC configuration shown in Figure 4 can be used. For details on how to choose R and C, see Table 73 on page 215. Figure 4. External RC Configuration
VCC NC
R
XTAL2 XTAL1
C GND
Timer Oscillator
For the Timer Oscillator pins, PC6(TOSC1) and PC7(TOSC2), the crystal is connected directly between the pins. No external capacitors are needed. The Oscillator is optimized for use with a 32.768 kHz watch crystal. Applying an external clock source to PC6(TOSC1) is not recommended.
7
1457G-AVR-09/03
Architectural Overview
The fast-access Register File concept contains 32 x 8-bit general purpose working registers with a single clock cycle access time. This means that during one single clock cycle, one Arithmetic Logic Unit (ALU) operation is executed. Two operands are output from the Register File, the operation is executed, and the result is stored back in the Register File - in one clock cycle. Six of the 32 registers can be used as three 16-bits indirect address register pointers for Data Space addressing - enabling efficient address calculations. One of the three address pointers is also used as the address pointer for look up tables in Flash Program memory. These added function registers are the 16-bits X-, Y-, and Z-register. The ALU supports arithmetic and logic operations between registers or between a constant and a register. Single register operations are also executed in the ALU. Figure 5 shows the ATmega323 AVR Enhanced RISC microcontroller architecture. In addition to the register operation, the conventional memory addressing modes can be used on the Register File as well. This is enabled by the fact that the Register File is assigned the 32 lowest Data Space addresses ($00 - $1F), allowing them to be accessed as though they were ordinary memory locations. The I/O Memory space contains 64 addresses for CPU peripheral functions as Control Registers, Timer/Counters, A/D Converters, and other I/O functions. The I/O Memory can be accessed directly, or as the Data Space locations following those of the Register File, $20 - $5F.
8
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Figure 5. The ATmega323 AVR Enhanced RISC Architecture
Data Bus 8-bit Interrupt Unit
16K X 16 Program Memory
Program Counter
Status and Control
SPI Unit Serial USART Serial TWI Bus 8-bit Timer/Counter with PWM 16-bit Timer/Counter with PWM 8-bit Timer/Counter with PWM Watchdog Timer
Instruction Register
32 x 8 General Purpose Registrers
Indirect Addressing
Instruction Decoder
Direct Addressing
ALU
Control Lines
2K x 8 Data SRAM
1K x 8 EEPROM
A/D Converter MUX and Gain
32 I/O Lines
Analog Comparator
The AVR uses a Harvard architecture concept - with separate memories and buses for Program and Data. The Program memory is executed with a single level pipelining. While one instruction is being executed, the next instruction is pre-fetched from the Program memory. This concept enables instructions to be executed in every clock cycle. The Program memory is In-System Reprogrammable Flash memory. With the jump and call instructions, the whole 16K address space is directly accessed. Most AVR instructions have a single 16-bit word format. Every Program memory address contains a 16- or 32-bit instruction. Program Flash memory space is divided in two sections, the Boot Program section (512 to 4K bytes, see page 177) and the Application Program section. Both sections have dedicated Lock bits for write and read/write protection. The SPM instruction that writes into the Application Flash memory section is allowed only in the Boot Program section. During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the Stack. The Stack is effectively allocated in the general data SRAM, and consequently the Stack size is only limited by the total SRAM size and the usage of the SRAM. All user programs must initialize the SP in the Reset Routine (before subroutines or interrupts are executed). The 12-bit Stack Pointer SP is read/write accessible in the I/O space.
9
1457G-AVR-09/03
The 2K bytes data SRAM can be easily accessed through the five different addressing modes supported in the AVR architecture. The memory spaces in the AVR architecture are all linear and regular memory maps. A flexible interrupt module has its control registers in the I/O space with an additional Global Interrupt Enable bit in the Status Register. All interrupts have a separate Interrupt Vector in the Interrupt Vector table. The interrupts have priority in accordance with their Interrupt Vector position. The lower the Interrupt Vector address, the higher the priority. Figure 6. Memory Maps
Program Memory $0000
Application Flash Section
Boot Flash Section $3FFF
10
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
The General Purpose Register File
Figure 7 shows the structure of the 32 general purpose working registers in the CPU. Figure 7. AVR CPU General Purpose Working Registers
7 R0 R1 R2 ... R13 General Purpose Working Registers R14 R15 R16 R17 ... R26 R27 R28 R29 R30 R31 $1A $1B $1C $1D $1E $1F X-register Low Byte X-register High Byte Y-register Low Byte Y-register High Byte Z-register Low Byte Z-register High Byte $0D $0E $0F $10 $11 0 Addr. $00 $01 $02
Most register operating instructions in the instruction set have direct access to all registers, and most of them are single cycle instructions. As shown in Figure 7, each register is also assigned a Data memory address, mapping them directly into the first 32 locations of the user Data Space. Although not being physically implemented as SRAM locations, this memory organization provides great flexibility in access of the registers, as the X-, Y-, and Z-registers can be set to index any register in the file. The X-register, Y-register, and Z-register The registers R26..R31 have some added functions to their general purpose usage. These registers are address pointers for indirect addressing of the Data Space. The three indirect address registers X, Y, and Z are defined as: Figure 8. The X-, Y-, and Z-registers
15 X - register 70 R27 ($1B) XH 0 XL 7 R26 ($1A) 0 0
15 Y - register 70 R29 ($1D)
YH 0
YL 7 R28 ($1C)
0 0
15 Z - register 70 R31 ($1F)
ZH 0
ZL 7 R30 ($1E)
0 0
In the different addressing modes these address registers have functions as fixed displacement, automatic increment and decrement (see the descriptions for the different instructions).
11
1457G-AVR-09/03
The ALU - Arithmetic Logic Unit
The high-performance AVR ALU operates in direct connection with all the 32 general purpose working registers. Within a single clock cycle, ALU operations between registers in the Register File are executed. The ALU operations are divided into three main categories - arithmetic, logical, and bit-functions. ATmega323 also provides a powerful multiplier supporting both signed/unsigned multiplication and fractional format. See the "Instruction Set" section for a detailed description. The ATmega323 contains 32K bytes On-chip In-System Reprogrammable Flash memory for program storage. Since all instructions are 16- or 32-bit words, the Flash is organized as 16K x 16. The Flash Program memory space is divided in two sections, Boot Program section and Application Program section. The Flash memory has an endurance of at least 1,000 write/erase cycles. The ATmega323 Program Counter (PC) is 14 bits wide, thus addressing the 16K Program memory locations. The operation of Boot Program section and associated Boot Lock bits for software protection are described in detail on page 177. See page 197 for a detailed description on Flash data serial downloading using the SPI pins. See page 202 for details on serial downloading using the JTAG Interface. Constant tables can be allocated within the entire Program memory address space (see the LPM - Load Program memory instruction description). See also page 13 for the different Program memory addressing modes.
The In-System Reprogrammable Flash Program Memory
The SRAM Data Memory
Figure 9 shows how the ATmega323 SRAM Memory is organized. The lower 2,144 Data memory locations address the Register File, the I/O Memory, and the internal data SRAM. The first 96 locations address the Register File + I/O Memory, and the next 2,048 locations address the internal data SRAM. The five different addressing modes for the Data memory cover: Direct, Indirect with Displacement, Indirect, Indirect with Pre-decrement, and Indirect with Post-increment. In the Register File, registers R26 to R31 feature the indirect addressing pointer registers. The direct addressing reaches the entire data space. The Indirect with Displacement mode features a 63 address locations reach from the base address given by the Y- or Z-register. When using register indirect addressing modes with automatic pre-decrement and postincrement, the address registers X, Y, and Z are decremented and incremented. The 32 general purpose working registers, 64 I/O Registers, and the 2,048 bytes of internal data SRAM in the ATmega323 are all accessible through all these addressing modes.
12
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Figure 9. SRAM Organization
Register File R0 R1 R2 ... R29 R30 R31 I/O Registers $00 $01 $02 ... $3D $3E $3F Data Address Space $0000 $0001 $0002 ... $001D $001E $001F $0020 $0021 $0022 ... $005D $005E $005F Internal SRAM $0060 $0061 ... $085E $085F
The Program and Data Addressing Modes
The ATmega323 AVR Enhanced RISC microcontroller supports powerful and efficient addressing modes for access to the Program memory (Flash) and Data memory (SRAM, Register File, and I/O Memory). This section describes the different addressing modes supported by the AVR architecture. In the figures, OP means the operation code part of the instruction word. To simplify, not all figures show the exact location of the addressing bits. Figure 10. Direct Single Register Addressing
Register Direct, Single Register Rd
The operand is contained in register d (Rd).
13
1457G-AVR-09/03
Register Direct, Two Registers Rd and Rr
Figure 11. Direct Register Addressing, Two Registers
Operands are contained in register r (Rr) and d (Rd). The result is stored in register d (Rd). I/O Direct Figure 12. I/O Direct Addressing
Operand address is contained in 6-bits of the instruction word. n is the destination or source register address. Data Direct Figure 13. Direct Data Addressing
Data Space
31 OP 16 LSBs 15
20 19 Rr/Rd
16
$0000
0
$085F
A 16-bit Data Address is contained in the 16 LSBs of a two-word instruction. Rd/Rr specify the destination or source register. 14
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Data Indirect with Displacement Figure 14. Data Indirect with Displacement
Data Space $0000 15 Y OR Z - REGISTER 0
15 OP
10 n
65 a
0
$085F
Operand address is the result of the Y- or Z-register contents added to the address contained in 6 bits of the instruction word. Data Indirect Figure 15. Data Indirect Addressing
Data Space $0000 15 X, Y OR Z - REGISTER 0
$085F
Operand address is the contents of the X-, Y-, or the Z-register. Data Indirect with Pre-decrement Figure 16. Data Indirect Addressing With Pre-decrement
Data Space $0000 15 X, Y OR Z - REGISTER 0
-1
$085F
The X-, Y-, or the Z-register is decremented before the operation. Operand address is the decremented contents of the X-, Y-, or the Z-register.
15
1457G-AVR-09/03
Data Indirect with Postincrement
Figure 17. Data Indirect Addressing With Post-increment
Data Space $0000 15 X, Y OR Z - REGISTER 0
1
$085F
The X-, Y-, or the Z-register is incremented after the operation. Operand address is the content of the X-, Y-, or the Z-register prior to incrementing. Constant Addressing Using Figure 18. Code Memory Constant Addressing the LPM and SPM Instructions
$3FFF
Constant byte address is specified by the Z-register contents. The 15 MSBs select word address (0 - 16K). For LPM, the LSB selects Low Byte if cleared (LSB = 0) or High Byte if set (LSB = 1). For SPM, the LSB should be cleared. Indirect Program Addressing, IJMP and ICALL Figure 19. Indirect Program Memory Addressing
$3FFF
Program execution continues at address contained by the Z-register (i.e., the PC is loaded with the contents of the Z-register).
16
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Relative Program Addressing, RJMP and RCALL Figure 20. Relative Program Memory Addressing
1
$3FFF
Program execution continues at address PC + k + 1. The relative address k is from - 2048 to 2047.
The EEPROM Data Memory
The ATmega323 contains 1K bytes of data EEPROM Memory. It is organized as a separate data space, in which single bytes can be read and written. The EEPROM has an endurance of at least 100,000 write/erase cycles. The access between the EEPROM and the CPU is described on page 66 specifying the EEPROM Address Registers, the EEPROM Data Register, and the EEPROM Control Register. For SPI data downloading of the EEPROM, see page 197 for a detailed description.
Memory Access Times and Instruction Execution Timing
This section describes the general access timing concepts for instruction execution and internal memory access. The AVR CPU is driven by the System Clock O, directly generated from the selected clock source for the chip. No internal clock division is used. Figure 21 shows the parallel instruction fetches and instruction executions enabled by the Harvard architecture and the fast-access Register File concept. This is the basic pipelining concept to obtain up to 1 MIPS per MHz with the corresponding unique results for functions per cost, functions per clocks, and functions per power-unit. Figure 21. The Parallel Instruction Fetches and Instruction Executions
T1 T2 T3 T4
System Clock O 1st Instruction Fetch 1st Instruction Execute 2nd Instruction Fetch 2nd Instruction Execute 3rd Instruction Fetch 3rd Instruction Execute 4th Instruction Fetch
Figure 22 shows the internal timing concept for the Register File. In a single clock cycle an ALU operation using two register operands is executed, and the result is stored back to the destination register.
17
1457G-AVR-09/03
Figure 22. Single Cycle ALU Operation
T1 T2 T3 T4
System Clock O Total Execution Time Register Operands Fetch ALU Operation Execute Result Write Back
The internal data SRAM access is performed in two System Clock cycles as described in Figure 23. Figure 23. On-chip Data SRAM Access Cycles
T1 T2 T3 T4
System Clock O Address Data WR Data RD
Prev. Address Address
I/O Memory
The I/O space definition of the ATmega323 is shown in Table 2. Table 2. ATmega323 I/O Space
I/O Address (SRAM Address) $3F ($5F) $3E ($5E) $3D ($5D) $3C ($3C) $3B ($5B) $3A ($5A) $39 ($59) $38 ($58) $37 ($57) $36 ($56) $35 ($55) $34 ($54) Name SREG SPH SPL OCR0 GICR GIFR TIMSK TIFR SPMCR TWCR MCUCR MCUCSR Function Status Register Stack Pointer High Stack Pointer Low Timer/Counter0 Output Compare Register General Interrupt Control Register General Interrupt Flag Register Timer/Counter Interrupt Mask Register Timer/Counter Interrupt Flag Register SPM Control Register Two-wire Serial Interface Control Register MCU general Control Register MCU general Control and Status Register
18
ATmega323(L)
1457G-AVR-09/03
Read
Write
ATmega323(L)
Table 2. ATmega323 I/O Space (Continued)
I/O Address (SRAM Address) $33 ($53) $32 ($52) $31 ($51)(1) $30 ($50) $2F ($4F) $2E ($4E) $2D ($4D) $2C ($4C) $2B ($4B) $2A ($4A) $29 ($49) $28 ($48) $27 ($47) $26 ($46) $25 ($45) $24 ($44) $23 ($43) $22 ($42) $21 ($41) $20 ($40)(2) $1F ($3F) $1E ($3E) $1D ($3D) $1C ($3C) $1B ($3B) $1A ($3A) $19 ($39) $18 ($38) $17 ($37) $16 ($36) $15 ($35) $14 ($34) $13 ($33) Name TCCR0 TCNT0 OSCCAL OCDR SFIOR TCCR1A TCCR1B TCNT1H TCNT1L OCR1AH OCR1AL OCR1BH OCR1BL ICR1H ICR1L TCCR2 TCNT2 OCR2 ASSR WDTCR UBRRH UCSRC EEARH EEARL EEDR EECR PORTA DDRA PINA PORTB DDRB PINB PORTC DDRC PINC Function Timer/Counter0 Control Register Timer/Counter0 (8-bit) Oscillator Calibration Register On-chip Debug Register Special Function I/O Register Timer/Counter1 Control Register A Timer/Counter1 Control Register B Timer/Counter1 High Byte Timer/Counter1 Low Byte Timer/Counter1 Output Compare Register A High Byte Timer/Counter1 Output Compare Register A Low Byte Timer/Counter1 Output Compare Register B High Byte Timer/Counter1 Output Compare Register B Low Byte T/C 1 Input Capture Register High Byte T/C 1 Input Capture Register Low Byte Timer/Counter2 Control Register Timer/Counter2 (8-bit) Timer/Counter2 Output Compare Register Asynchronous Mode Status Register Watchdog Timer Control Register USART Baud Rate Register High Byte USART Control and Status Register C EEPROM Address Register High Byte EEPROM Address Register Low Byte EEPROM Data Register EEPROM Control Register Data Register, Port A Data Direction Register, Port A Input Pins, Port A Data Register, Port B Data Direction Register, Port B Input Pins, Port B Data Register, Port C Data Direction Register, Port C Input Pins, Port C
19
1457G-AVR-09/03
Table 2. ATmega323 I/O Space (Continued)
I/O Address (SRAM Address) $12 ($32) $11 ($31) $10 ($30) $0F ($2F) $0E ($2E) $0D ($2D) $0C ($2C) $0B ($2B) $0A ($2A) $09 ($29) $08 ($28) $07 ($27) $06 ($26) $05 ($25) $04 ($24) $03 ($23) $02 ($22) $01 ($21) $00 ($20) Notes: Name PORTD DDRD PIND SPDR SPSR SPCR UDR UCSRA UCSRB UBRRL ACSR ADMUX ADCSR ADCH ADCL TWDR TWAR TWSR TWBR Function Data Register, Port D Data Direction Register, Port D Input Pins, Port D SPI I/O Data Register SPI Status Register SPI Control Register USART I/O Data Register USART Control and Status Register A USART Control and Status Register B USART Baud Rate Register Low Byte Analog Comparator Control and Status Register ADC Multiplexer Select Register ADC Control and Status Register ADC Data Register High ADC Data Register Low Two-wire Serial Interface Data Register Two-wire Serial Interface (Slave) Address Register Two-wire Serial Interface Status Register Two-wire Serial Interface Bit Rate Register
1. When the OCDEN Fuse is unprogrammed, the OSCCAL Register is always accessed on this address. Refer to the debugger specific documentation for details on how to use the OCDR Register. 2. Refer to the USART description for details on how to access UBRRH and UCSRC.
All ATmega323 I/Os and peripherals are placed in the I/O space. The I/O locations are accessed by the IN and OUT instructions, transferring data between the 32 general purpose working registers and the I/O space. I/O Registers within the address range $00 $1F are directly bit-accessible using the SBI and CBI instructions. In these registers, the value of single bits can be checked by using the SBIS and SBIC instructions. Refer to the instruction set chapter for more details. When using the I/O specific commands IN and OUT, the I/O addresses $00 - $3F must be used. When addressing I/O Registers as SRAM, $20 must be added to these addresses. All I/O Register addresses throughout this document are shown with the SRAM address in parentheses. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O Memory addresses should never be written. Some of the Status Flags are cleared by writing a logical one to them. Note that the CBI and SBI instructions will operate on all bits in the I/O Register, writing a one back into any flag read as set, thus clearing the flag. The CBI and SBI instructions work with registers $00 to $1F only. The I/O and Peripherals Control Registers are explained in the following sections.
20
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
The Status Register - SREG The AVR Status Register - SREG - at I/O space location $3F ($5F) is defined as:
Bit $3F ($5F) Read/Write Initial Value 7 I R/W 0 6 T R/W 0 5 H R/W 0 4 S R/W 0 3 V R/W 0 2 N R/W 0 1 Z R/W 0 0 C R/W 0 SREG
* Bit 7 - I: Global Interrupt Enable The Global Interrupt Enable bit must be set (one) for the interrupts to be enabled. The individual Interrupt Enable control is then performed in separate control registers. If the Global Interrupt Enable Register is cleared (zero), none of the interrupts are enabled independent of the individual interrupt enable settings. The I-bit is cleared by hardware after an interrupt has occurred, and is set by the RETI instruction to enable subsequent interrupts. * Bit 6 - T: Bit Copy Storage The Bit Copy Instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source and destination for the operated bit. A bit from a register in the Register File can be copied into T by the BST instruction, and a bit in T can be copied into a bit in a register in the Register File by the BLD instruction. * Bit 5 - H: Half Carry Flag The Half Carry Flag H indicates a Half Carry in some arithmetic operations. See the "Instruction Set Description" for detailed information. * Bit 4 - S: Sign Bit, S = N
V
The S-bit is always an exclusive or between the Negative Flag N and the Two's Complement Overflow Flag V. See the "Instruction Set Description" for detailed information. * Bit 3 - V: Two's Complement Overflow Flag The Two's Complement Overflow Flag V supports two's complement arithmetics. See the "Instruction Set Description" for detailed information. * Bit 2 - N: Negative Flag The Negative Flag N indicates a negative result in an arithmetic or logic operation. See the "Instruction Set Description" for detailed information. * Bit 1 - Z: Zero Flag The Zero Flag Z indicates a zero result in an arithmetic or logic operation. See the "Instruction Set Description" for detailed information. * Bit 0 - C: Carry Flag The Carry Flag C indicates a Carry in an arithmetic or logic operation. See the "Instruction Set Description" for detailed information. Note that the Status Register is not automatically stored when entering an interrupt routine and restored when returning from an interrupt routine. This must be handled by software.
21
1457G-AVR-09/03
The Stack Pointer - SP
The ATmega323 Stack Pointer is implemented as two 8-bit registers in the I/O space locations $3E ($5E) and $3D ($5D). As the ATmega323 Data memory has $860 locations, 12 bits are used.
Bit $3E ($5E) $3D ($5D) 15 - SP7 7 Read/Write R R/W Initial Value 0 0 14 - SP6 6 R R/W 0 0 13 - SP5 5 R R/W 0 0 12 - SP4 4 R R/W 0 0 11 SP11 SP3 3 R/W R/W 0 0 10 SP10 SP2 2 R/W R/W 0 0 9 SP9 SP1 1 R/W R/W 0 0 8 SP8 SP0 0 R/W R/W 0 0 SPH SPL
The Stack Pointer points to the data SRAM Stack area where the Subroutine and Interrupt Stacks are located. This Stack space in the data SRAM must be defined by the program before any subroutine calls are executed or interrupts are enabled. The Stack Pointer must be set to point above $60. The Stack Pointer is decremented by one when data is pushed onto the Stack with the PUSH instruction, and it is decremented by two when the return address is pushed onto the Stack with subroutine call and interrupt. The Stack Pointer is incremented by one when data is popped from the Stack with the POP instruction, and it is incremented by two when data is popped from the Stack with return from subroutine RET or return from interrupt RETI.
Reset and Interrupt Handling
The ATmega323 provides nineteen different interrupt sources. These interrupts and the separate Reset Vector, each have a separate Program Vector in the Program memory space. All interrupts are assigned individual enable bits which must be set (one) together with the I-bit in the Status Register in order to enable the interrupt. Depending on the Program Counter value, interrupts may be disabled when Boot Lock bits BLB02 or BLB12 are set. See the section "Boot Loader Support" on page 177 for details The lowest addresses in the Program memory space are automatically defined as the Reset and Interrupt Vectors. The complete list of vectors is shown in Table 3. The list also determines the priority levels of the different interrupts. The lower the address the higher is the priority level. RESET has the highest priority, and next is INT0 - the External Interrupt Request 0, etc. The Interrupt Vectors can be moved to the start of the boot Flash section by setting the IVSEL bit in the General Interrupt Control Register (GICR). See the GICR description on page 33 for details.. Table 3. Reset and Interrupt Vectors
Vector No. 1 2 3 4 5 6 7 8 9 Program Address(2) $000(1) $002 $004 $006 $008 $00A $00C $00E $010 Source RESET INT0 INT1 INT2 TIMER2 COMP TIMER2 OVF TIMER1 CAPT TIMER1 COMPA TIMER1 COMPB Interrupt Definition External Pin, Power-on Reset, Brown-out Reset and Watchdog Reset External Interrupt Request 0 External Interrupt Request 1 External Interrupt Request 2 Timer/Counter2 Compare Match Timer/Counter2 Overflow Timer/Counter1 Capture Event Timer/Counter1 Compare Match A Timer/Counter1 Compare Match B
22
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Table 3. Reset and Interrupt Vectors (Continued)
Vector No. 10 11 12 13 14 15 16 17 18 19 20 Notes: Program Address(2) $012 $014 $016 $018 $01A $01C $01E $020 $022 $024 $026 Source TIMER1 OVF TIMER0 COMP TIMER0 OVF SPI, STC USART, RXC USART, UDRE USART, TXC ADC EE_RDY ANA_COMP TWSI Interrupt Definition Timer/Counter1 Overflow Timer/Counter0 Compare Match Timer/Counter0 Overflow Serial Transfer Complete USART, Rx Complete USART Data Register Empty USART, Tx Complete ADC Conversion Complete EEPROM Ready Analog Comparator Two-wire Serial Interface
1. When the BOOTRST Fuse is programmed, the device will jump to the Boot Loader address at reset, see "Boot Loader Support" on page 177. 2. When the IVSEL bit in GICR is set, Interrupt Vectors will be moved to the start of the boot Flash section. The address of each Interrupt Vector will then be address in this table plus the start address of the boot Flash section.
Table 4 shows Reset and Interrupt Vectors placement for the various combinations of BOOTRST and IVSEL settings. Table 4. Reset and Interrupt Vectors Placement
BOOTRST 0 0 1 1 Note: IVSEL 0 1 0 1 Reset address $0000 $0000 Boot Reset Address Boot Reset Address Interrupt Vectors Start Address $0002 Boot Reset Address + $0002 $0002 Boot Reset Address + $0002
The Boot Reset Address is shown in Table 59 on page 177.
The most typical and general program setup for the Reset and Interrupt Vector Addresses in ATmega323 is:
Address $000 $002 $004 $006 $008 $00a $00c $00e $010 $012 $014 $016 Labels Code jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp RESET EXT_INT0 EXT_INT1 EXT_INT2 TIM2_COMP TIM2_OVF TIM1_CAPT Comments ; Reset Handler ; IRQ0 Handler ; IRQ1 Handler ; IRQ2 Handler ; Timer2 Compare Handler ; Timer2 Overflow Handler ; Timer1 Capture Handler
TIM1_COMPA ; Timer1 CompareA Handler TIM1_COMPB ; Timer1 CompareB Handler TIM1_OVF TIM0_COMP TIM0_OVF ; Timer1 Overflow Handler ; Timer0 Compare Handler ; Timer0 Overflow Handler
23
1457G-AVR-09/03
$018 $01a $01c $01e $020 $022 $024 $026 Handler ; $028 $029 $02a $02b $02c ... ...
jmp jmp jmp jmp jmp jmp jmp jmp
SPI_STC; USART_RXC USART_TXC ADC EE_RDY ANA_COMP TWSI
; SPI Transfer Complete Handler ; USART RX Complete Handler ; USART TX Complete Handler ; ADC Conversion Complete Interrupt Handler ; EEPROM Ready Handler ; Analog Comparator Handler ; Two-wire Serial Interface Interrupt
USART_UDRE ; UDR Empty Handler
MAIN: ldi out ldi out ...
r16,high(RAMEND); Main program start SPH,r16 ; Set Stack Pointer to top of RAM
r16,low(RAMEND) SPL,r16 xxx

When the BOOTRST Fuse is unprogrammed, the boot section size set to 4K bytes and the IVSEL bit in the GICR Register is set before any interrupts are enabled, the most typical and general program setup for the Reset and Interrupt Vector Addresses are:
Address $000 ; $002 $003 $004 $005 $006 ; .org $3802 $3802 $3804 ... $3826 Handler jmp jmp ... jmp EXT_INT0 EXT_INT1 ... TWSI ; IRQ0 Handler ; IRQ1 Handler ; ; Two-wire Serial Interface Interrupt MAIN: Labels Code jmp ldi out ldi out RESET Comments ; Reset handler
r16,high(RAMEND); Main program start SPH,r16 SPL,r16 xxx ; Set Stack Pointer to top of RAM r16,low(RAMEND)

When the BOOTRST Fuse is programmed and the boot section size set to 4K bytes, the most typical and general program setup for the Reset and Interrupt Vector Addresses are:
Address .org $002 $002 $004 ... $026 Handler ; $028 $029 MAIN: ldi out r16,high(RAMEND); Main program start SPH,r16 ; Set Stack Pointer to top of RAM jmp jmp ... jmp EXT_INT0 EXT_INT1 ... TWSI ; IRQ0 Handler ; IRQ1 Handler ; ; Two-wire Serial Interface Interrupt Labels Code Comments
24
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
$02a $02b $02c ; .org $3800 $3800 ... ... jmp ... RESET ... ; Reset handler ldi out r16,low(RAMEND) SPL,r16 xxx

When the BOOTRST Fuse is programmed, the boot section size set to 4K bytes and the IVSEL bit in the GICR Register is set before any interrupts are enabled, the most typical and general program setup for the Reset and Interrupt Vector Addresses are:
Address Labels Code $000 $001 $002 $003 $004 ; .org $3800 $3800 $3802 $3804 ... $3826 jmp jmp jmp ... jmp RESET ; Reset handler EXT_INT0 ; IRQ0 Handler EXT_INT1 ; IRQ1 Handler ... TWSI ; ; Two-wire Serial Interface Interrupt Handler MAIN: ldi out ldi out SPH,r16 Comments r16,high(RAMEND); Main program start ; Set Stack Pointer to top of RAM
r16,low(RAMEND) SPL,r16 xxx

Reset Sources
The ATmega323 has five sources of reset: * * * * * Power-on Reset. The MCU is reset when the supply voltage is below the Power-on Reset threshold (VPOT). External Reset. The MCU is reset when a low level is present on the RESET pin for more than 500 ns. Watchdog Reset. The MCU is reset when the Watchdog timer period expires and the Watchdog is enabled. Brown-out Reset. The MCU is reset when the supply voltage VCC is below the Brown-out Reset threshold (VBOT). JTAG AVR Reset. The MCU is reset as long as there is a logic one in the Reset Register, one of the scan chains of the JTAG system.
During Reset, all I/O Registers are set to their initial values, and the program starts execution from the Reset Vector. The instruction placed at the Reset Vector must be a JMP - Absolute Jump - instruction to the reset handling routine. If the program never enables an interrupt source, the Interrupt Vectors are not used, and regular program code can be placed at these locations. This is also the case if the Reset Vector is in the Application section while the Interrupt Vectors are in the Boot section or vice versa. The circuit diagram in Figure 24 shows the Reset Logic. Table 5 and Table 6 define the timing and electrical parameters of the reset circuitry.
25
1457G-AVR-09/03
Figure 24. Reset Logic
DATA BUS
MCU Control and Status Register (MCUCSR)
PORF BORF EXTRF WDRF JTRF
VCC
Power-on Reset Circuit
BODEN BODLEVEL 100-500k RESET
SPIKE FILTER
Brown-out Reset Circuit
Reset Circuit
Counter Reset
JTAG Reset Register
Watchdog Timer
On-chip RC Oscillator
Clock Generator
CK
Delay Counters TIMEOUT
CKSEL[3:0]
Table 5. Reset Characteristics(1)
Symbol Parameter Power-on Reset Threshold Voltage (rising) VPOT Power-on Reset Threshold Voltage (falling)(2) RESET Pin Threshold Voltage Brown-out Reset Threshold Voltage (BODLEVEL = 1) (BODLEVEL = 0) Condition Min 1.0 0.4 Typ 1.4 0.6 Max 1.8 0.8 Units V V
VRST VBOT Notes:
0.1VCC 2.4 3.5
- 2.7 4.0
0.9VCC 3.2
V
V 4.5
1. Values are guidelines only. Actual values are TBD. 2. The Power-on Reset will not work unless the supply voltage has been below VPOT (falling)
26
ATmega323(L)
1457G-AVR-09/03
Internal Reset
ATmega323(L)
Table 6. Reset Delay Selections(1)
Start-up Time, VCC = 2.7V, BODLEVEL Unprogrammed 4.2 ms + 6 CK 30 s + 6 CK(4) 67 ms + 6 CK 4.2 ms + 6 CK 30 s + 6 CK(4) 67 ms + 6 CK 4.2 ms + 6 CK 30 s + 6 CK(4) 67 ms + 32K CK 67 ms + 1K CK 67 ms + 16K CK 4.2 ms + 16K CK 30 s + 16K CK(4) Start-up Time, VCC = 4.0V, BODLEVEL Programmed 5.8 ms + 6 CK 10 s + 6 CK(5) 92 ms + 6 CK 5.8 ms + 6 CK 10 s + 6 CK(5) 92 ms + 6 CK 5.8 ms + 6 CK 10 s + 6 CK(5) 92 ms + 32K CK 92 ms + 1K CK 92 ms + 16K CK 5.8 ms + 16K CK 10 s + 16K CK(5)
CKSEL(2) 0000 0001 0010
(6)
Recommended Usage(3) Ext. Clock, Fast Rising Power Ext. Clock, BOD Enabled Int. RC Oscillator, Slowly Rising Power Int. RC Oscillator, Fast Rising Power Int. RC Oscillator, BOD Enabled Ext. RC Oscillator, Slowly Rising Power Ext. RC Oscillator, Fast Rising Power Ext. RC Oscillator, BOD Enabled Ext. Low-frequency Crystal Ext. Low-frequency Crystal Crystal Oscillator, Slowly Rising Power Crystal Oscillator, Fast Rising Power Crystal Oscillator, BOD Enabled Ceramic Resonator/Ext. Clock, Slowly Rising Power Ceramic Resonator, Fast Rising Power Ceramic Resonator, BOD Enabled
0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101
67 ms 1K CK 1110 1111 Notes: 1. 2. 3. 4. 5. 6.
92 ms + 1K CK
4.2 ms + 1K CK 30 s + 1K CK(4)
5.8 ms + 1K CK 10 s + 1K CK(5)
On Power-up, the start-up time is increased with Typ 0.6 ms. "1" means unprogrammed, "0" means programmed. For possible clock selections, see "Clock Options" on page 6. When BODEN is programmed, add 100 s. When BODEN is programmed, add 25 s. Default value.
27
1457G-AVR-09/03
Table 6 shows the start-up times from Reset. When the CPU wakes up from Powerdown or Power-save, only the clock counting part of the start-up time is used. The Watchdog Oscillator is used for timing the Real Time part of the start-up time. The number WDT Oscillator cycles used for each time-out is shown in Table 7. The frequency of the Watchdog Oscillator is voltage dependent as shown in the Electrical Characteristics section. The device is shipped with CKSEL = "0010" (Internal RC Oscillator, slowly rising power). Table 7. Number of Watchdog Oscillator Cycles
BODLEVEL(1) Unprogrammed Unprogrammed Unprogrammed Unprogrammed Programmed Programmed Programmed Programmed Note: VCC Condition 2.7V 2.7V 2.7V 2.7V 4.0V 4.0V 4.0V 4.0V Time-out 30 s 130 s 4.2 ms 67 ms 10 s 35 s 5.8 ms 92 ms Number of Cycles 8 32 1K 16K 8 32 4K 64K
1. The BODLEVEL Fuse can be used to select start-up times even if the Brown-out Detection is disabled (BODEN Fuse unprogrammed).
Power-on Reset
A Power-on Reset (POR) pulse is generated by an On-chip detection circuit. The detection level is defined in Table 5. The POR is activated whenever VCC is below the detection level. The POR circuit can be used to trigger the Start-up Reset, as well as to detect a failure in supply voltage. A Power-on Reset (POR) circuit ensures that the device is reset from Power-on. Reaching the Power-on Reset threshold voltage invokes a delay counter, which determines the delay, for which the device is kept in RESET after VCC rise. The time-out period of the delay counter can be defined by the user through the CKSEL Fuses. The different selections for the delay period are presented in Table 6. The RESET signal is activated again, without any delay, when the VCC decreases below detection level. Figure 25. MCU Start-up, RESET Tied to VCC
VCC VPOT
RESET
VRST
TIME-OUT
tTOUT
INTERNAL RESET
28
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Figure 26. MCU Start-up, RESET Extended Externally
VCC VPOT
RESET
VRST
TIME-OUT
tTOUT
INTERNAL RESET
External Reset
An External Reset is generated by a low level on the RESET pin. Reset pulses longer than 500 ns will generate a reset, even if the clock is not running. Shorter pulses are not guaranteed to generate a reset. When the applied signal reaches the Reset Threshold Voltage - VRST on its positive edge, the delay timer starts the MCU after the Time-out Period tTOUT has expired. Figure 27. External Reset During Operation
Brown-out Detection
ATmega323 has an On-chip Brown-out Detection (BOD) circuit for monitoring the VCC level during the operation. The BOD circuit can be enabled/disabled by the fuse BODEN. When the BOD is enabled (BODEN programmed), and VCC decreases to a value below the trigger level, the Brown-out Reset is immediately activated. When VCC increases above the trigger level, the Brown-out Reset is deactivated after a delay. The delay is defined by the user in the same way as the delay of POR signal, in Table 6. The trigger level for the BOD can be selected by the fuse BODLEVEL to be 2.7V (BODLEVEL unprogrammed), or 4.0V (BODLEVEL programmed). The trigger level has a hysteresis of 50 mV to ensure spike free Brown-out Detection. The BOD circuit will only detect a drop in VCC if the voltage stays below the trigger level for longer than 9 s for trigger level 4.0V, 21 s for trigger level 2.7V (typical values).
29
1457G-AVR-09/03
Figure 28. Brown-out Reset During Operation
VCC VBOTVBOT+
RESET
TIME-OUT
tTOUT
INTERNAL RESET
The hysteresis on VBOT: VBOT+ = VBOT + 25 mV, VBOT- = VBOT - 25 mV Watchdog Reset When the Watchdog times out, it will generate a short reset pulse of 1 CK cycle duration. On the falling edge of this pulse, the delay timer starts counting the Time-out Period tTOUT. Refer to page 64 for details on operation of the Watchdog Timer. Figure 29. Watchdog Reset During Operation
CK
MCU Control and Status Register - MCUCSR
The MCU Control and Status Register contains control bits for general MCU functions, and provides information on which reset source caused an MCU Reset.
Bit $34 ($54) Read/Write Initial Value 7 JTD R/W 0 6 ISC2 R/W 0 5 - R 0 4 JTRF R/W 3 WDRF R/W 2 BORF R/W 1 EXTRF R/W 0 PORF R/W MCUCSR
See Bit Description
* Bit 7 - JTD: JTAG Interface Disable When this bit is cleared (zero), the JTAG interface is enabled if the JTAGEN Fuse is programmed. If this bit is set (one), the JTAG interface is disabled. To avoid unintentional disabling of the JTAG interface, the user software must write this bit as one twice within four cycles to set the bit. If the JTAG interface is left unconnected to other JTAG circuitry, the JTD bit should be set to one. The reason for this is to avoid static current at the TDO pin in the JTAG interface.
30
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
* Bit 6 - ISC2: Interrupt Sense Control 2 The asynchronous external interrupt 2 is activated by the external pin INT2 if the SREG I-flag and the corresponding interrupt mask in the GICR are set. If ISC2 is cleared (zero), a falling edge on INT2 activates the interrupt. If ISC2 is set (one) a rising edge on INT2 activates the interrupt. Edges on INT2 are registered asynchronously. Pulses on INT2 wider than 50 ns will generate an interrupt. Shorter pulses are not guaranteed to generate an interrupt. When changing the ISC2 bit, an interrupt can occur. Therefore, it is recommended to first disable INT2 by clearing its Interrupt Enable bit in the GICR Register. Then, the ISC2 bit can be changed. Finally, the INT2 Interrupt Flag should be cleared by writing a logical one to its Interrupt Flag bit in the GIFR Register before the interrupt is re-enabled. * Bit 5 - Res: Reserved Bit This bit is a reserved bit in the ATmega323 and always reads as zero. * Bit 4 - JTRF: JTAG Reset Flag This bit is set if a reset is being caused by a logic one in the JTAG Reset Register selected by the JTAG instruction AVR_RESET. This bit is reset by a Power-on Reset, or by writing a logic zero to the flag. * Bit 3 - WDRF: Watchdog Reset Flag This bit is set if a Watchdog Reset occurs. The bit is reset by a Power-on Reset, or by writing a logic zero to the flag. * Bit 2 - BORF: Brown-out Reset Flag This bit is set if a Brown-out Reset occurs. The bit is reset by a Power-on Reset, or by writing a logic zero to the flag. * Bit 1 - EXTRF: External Reset Flag This bit is set if an External Reset occurs. The bit is reset by a Power-on Reset, or by writing a logic zero to the flag. * Bit 0 - PORF: Power-on Reset Flag This bit is set if a Power-on Reset occurs. The bit is reset only by writing a logic zero to the flag. To make use of the Reset Flags to identify a reset condition, the user should read and then reset the MCUCSR as early as possible in the program. If the register is cleared before another reset occurs, the source of the reset can be found by examining the Reset Flags. Internal Voltage Reference ATmega323 features an internal bandgap reference with a nominal voltage of 1.22V. This reference is used for Brown-out Detection, and it can be used as an input to the Analog Comparator or the ADC. The 2.56V reference to the ADC is generated from the internal bandgap reference.
31
1457G-AVR-09/03
Voltage Reference Enable Signals and Start-up Time
The voltage reference has a start-up time that may influence the way it should be used. The maximum start-up time is TBD. To save power, the reference is not always turned on. The reference is on during the following situations: 1. When the BOD is enabled (by programming the BODEN Fuse). 2. When the bandgap reference is connected to the Analog Comparator (by setting the ACBG bit in ACSR). 3. When the ADC is enabled. Thus, when the BOD is not enabled, after setting the ACBG bit, the user must always allow the reference to start up before the output from the Analog Comparator is used. The bandgap reference uses typically 10 A, and to reduce power consumption in Power-down mode, the user can avoid the three conditions above to ensure that the reference is turned off before entering Power-down mode.
Interrupt Handling
The ATmega323 has two 8-bit Interrupt Mask Control Registers: GICR - General Interrupt Control Register and TIMSK - Timer/Counter Interrupt Mask Register. When an interrupt occurs, the Global Interrupt Enable I-bit is cleared (zero) and all interrupts are disabled. The user software can set (one) the I-bit to enable nested interrupts. The I-bit is set (one) when a Return from Interrupt instruction - RETI - is executed. When the Program Counter is vectored to the actual Interrupt Vector in order to execute the interrupt handling routine, hardware clears the corresponding flag that generated the interrupt. Some of the Interrupt Flags can also be cleared by writing a logic one to the flag bit position(s) to be cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is cleared (zero), the Interrupt Flag will be set and remembered until the interrupt is enabled, or the flag is cleared by software. If one or more interrupt conditions occur while the Global Interrupt Enable bit is cleared (zero), the corresponding Interrupt Flag(s) will be set and remembered until the Global Interrupt Enable bit is set (one), and will be executed by order of priority. Note that external level interrupt does not have a flag, and will only be remembered for as long as the interrupt condition is present. Note that the Status Register is not automatically stored when entering an interrupt routine and restored when returning from an interrupt routine. This must be handled by software.
Interrupt Response Time
The interrupt execution response for all the enabled AVR interrupts is four clock cycles minimum. After four clock cycles the Program Vector address for the actual interrupt handling routine is executed. During this four clock cycle period, the Program Counter (14 bits) is pushed onto the Stack. The vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. If an interrupt occurs during execution of a multicycle instruction, this instruction is completed before the interrupt is served. If an interrupt occurs when the MCU is in sleep mode, the interrupt execution response time is increased by four clock cycles. A return from an interrupt handling routine takes four clock cycles. During these four clock cycles, the Program Counter (two bytes) is popped back from the Stack, the Stack Pointer is incremented by two, and the I-flag in SREG is set. When AVR exits from an interrupt, it will always return to the main program and execute one more instruction before any pending interrupt is served.
32
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
The General Interrupt Control Register - GICR
l
Bit $3B ($5B) Read/Write Initial Value
7 INT1 R/W 0
6 INT0 R/W 0
5 INT2 R/W 0
4 - R 0
3 - R 0
2 - R 0
1 IVSEL R/W 0
0 IVCE R/W 0 GICR
* Bit 7 - INT1: External Interrupt Request 1 Enable When the INT1 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), the external pin interrupt is activated. The Interrupt Sense Control1 bits 1/0 (ISC11 and ISC10) in the MCU general Control Register (MCUCR) define whether the external interrupt is activated on rising and/or falling edge of the INT1 pin or level sensed. Activity on the pin will cause an interrupt request even if INT1 is configured as an output. The corresponding interrupt of External Interrupt Request 1 is executed from the INT1 Interrupt Vector. See also "External Interrupts" on page 37. * Bit 6 - INT0: External Interrupt Request 0 Enable When the INT0 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), the external pin interrupt is activated. The Interrupt Sense Control0 bits 1/0 (ISC01 and ISC00) in the MCU general Control Register (MCUCR) define whether the external interrupt is activated on rising or falling edge of the INT0 pin or level sensed. Activity on the pin will cause an interrupt request even if INT0 is configured as an output. The corresponding interrupt of External Interrupt Request 0 is executed from the INT0 Interrupt Vector. See also "External Interrupts" on page 37. * Bit 5 - INT2: External Interrupt Request 2 Enable When the INT2 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), the external pin interrupt is activated. The Interrupt Sense Control2 bit (ISC02) in the MCU Control and Status Register (MCUCSR) defines whether the external interrupt is activated on rising or falling edge of the INT2 pin. Activity on the pin will cause an interrupt request even if INT2 is configured as an output. The corresponding interrupt of External Interrupt Request 2 is executed from the INT2 Interrupt Vector. See also "External Interrupts" on page 37. * Bits 4..2 - Res: Reserved Bits These bits are reserved bits in the ATmega323 and always read as zero. * Bit 1 - IVSEL: Interrupt Vector Select When the IVSEL bit is cleared (zero), the Interrupt Vectors are placed at the start of the Flash memory. When this bit is set (one), the Interrupt Vectors are moved to the beginning of the Boot Loader section of the Flash. The actual address to the start of the Boot Flash section is determined by the BOOTSZ Fuses. Refer to the section "Boot Loader Support" on page 177 for details. To avoid unintentional changes of Interrupt Vector tables, a special write procedure must be followed to change the IVSEL bit: 1. Set the Interrupt Vector Change Enable (IVCE) bit. 2. Within four cycles, write the desired value to IVSEL while writing a zero to IVCE. Interrupts will be automatically disabled while this sequence is executed. Interrupts are disabled in the cycle IVCE is set, and they remain disabled until after the instruction following the write to IVSEL. If IVSEL is not written, interrupts remain disabled in four cycles. The I-flag in the Status Register is unaffected by the automatic disabling.
33
1457G-AVR-09/03
Note: If Boot Lock bits BLB02 or BLB12 are set, changing the Interrupt Vector table will change from what part of the Program memory interrupts are allowed. Refer to the section "Boot Loader Support" on page 177 for details on Boot Lock bits. * Bit 0 - IVCE: Interrupt Vector Change Enable The IVCE bit must be set to enable change of the IVSEL bit. IVCE is cleared by hardware four cycles after it is written or when IVSEL is written. Setting the IVCE bit will disable interrupts, as explained in the IVSEL description above. The General Interrupt Flag Register - GIFR
Bit $3A ($5A) Read/Write Initial Value
7 INTF1 R/W 0
6 INTF0 R/W 0
5 INTF2 R/W 0
4 - R 0
3 - R 0
2 - R 0
1 - R 0
0 - R 0 GIFR
* Bit 7 - INTF1: External Interrupt Flag1 When an event on the INT1 pin triggers an interrupt request, INTF1 becomes set (one). If the I-bit in SREG and the INT1 bit in GICR are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. This flag is always cleared when INT1 is configured as a level interrupt. * Bit 6 - INTF0: External Interrupt Flag0 When an event on the INT0 pin triggers an interrupt request, INTF0 becomes set (one). If the I-bit in SREG and the INT0 bit in GICR are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. This flag is always cleared when INT0 is configured as a level interrupt. * Bit 5 - INTF2: External Interrupt Flag2 When an event on the INT2 pin triggers an interrupt request, INTF2 becomes set (one). If the I-bit in SREG and the INT2 bit in GICR are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. * Bits 4..0 - Res: Reserved Bits These bits are reserved bits in the ATmega323 and always read as zero. The Timer/Counter Interrupt Mask Register - TIMSK
Bit $39 ($59) Read/Write Initial Value
7 OCIE2 R/W 0
6 TOIE2 R/W 0
5 TICIE1 R/W 0
4 OCIE1A R/W 0
3 OCIE1B R/W 0
2 TOIE1 R/W 0
1 OCIE0 R/W 0
0 TOIE0 R/W 0 TIMSK
* Bit 7 - OCIE2: Timer/Counter2 Output Compare Match Interrupt Enable When the OCIE2 bit is set (one) and the I-bit in the Status Register is set (one), the Timer/Counter2 Compare Match interrupt is enabled. The corresponding interrupt is executed if a compare match in Timer/Counter2 occurs, i.e. when the OCF2 bit is set in the Timer/Counter Interrupt Flag Register - TIFR.
34
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
* Bit 6 - TOIE2: Timer/Counter2 Overflow Interrupt Enable When the TOIE2 bit is set (one) and the I-bit in the Status Register is set (one), the Timer/Counter2 Overflow interrupt is enabled. The corresponding interrupt is executed if an ov erflow in Timer/Counter2 occurs, i.e., when the TOV2 bit is set in the Timer/Counter Interrupt Flag Register - TIFR. * Bit 5 - TICIE1: Timer/Counter1 Input Capture Interrupt Enable When the TICIE1 bit is set (one) and the I-bit in the Status Register is set (one), the Timer/Counter1 Input Capture Event Interrupt is enabled. The corresponding interrupt is executed if a capture triggering event occurs on PD6 (ICP), i.e., when the ICF1 bit is set in the Timer/Counter Interrupt Flag Register - TIFR. * Bit 4 - OCIE1A: Timer/Counter1 Output Compare A Match Interrupt Enable When the OCIE1A bit is set (one) and the I-bit in the Status Register is set (one), the Timer/Counter1 Compare A Match interrupt is enabled. The corresponding interrupt is executed if a Compare A Match in Timer/Counter1 occurs, i.e., when the OCF1A bit is set in the Timer/Counter Interrupt Flag Register - TIFR. * Bit 3 - OCIE1B: Timer/Counter1 Output Compare B Match Interrupt Enable When the OCIE1B bit is set (one) and the I-bit in the Status Register is set (one), the Timer/Counter1 Compare B Match interrupt is enabled. The corresponding interrupt is executed if a Compare B Match in Timer/Counter1 occurs, i.e., when the OCF1B bit is set in the Timer/Counter Interrupt Flag Register - TIFR. * Bit 2 - TOIE1: Timer/Counter1 Overflow Interrupt Enable When the TOIE1 bit is set (one) and the I-bit in the Status Register is set (one), the Timer/Counter1 Overflow interrupt is enabled. The corresponding interrupt is executed if an ov erflow in Timer/Counter1 occurs, i.e., when the TOV1 bit is set in the Timer/Counter Interrupt Flag Register - TIFR. * Bit 1 - OCIE0: Timer/Counter0 Output Compare Match Interrupt Enable When the OCIE0 bit is set (one) and the I-bit in the Status Register is set (one), the Timer/Counter0 Compare Match interrupt is enabled. The corresponding interrupt is executed if a Compare0 Match in Timer/Counter0 occurs, i.e., when the OCF0 bit is set in the Timer/Counter Interrupt Flag Register - TIFR. * Bit 0 - TOIE0: Timer/Counter0 Overflow Interrupt Enable When the TOIE0 bit is set (one) and the I-bit in the Status Register is set (one), the Timer/Counter0 Overflow interrupt is enabled. The corresponding interrupt is executed if an overflow in Timer/Counter0 occurs, i.e. when the TOV0 bit is set in the Timer/Counter Interrupt Flag Register - TIFR.
35
1457G-AVR-09/03
The Timer/Counter Interrupt Flag Register - TIFR
Bit $38 ($58) Read/Write Initial Value
7 OCF2 R/W 0
6 TOV2 R/W 0
5 ICF1 R/W 0
4 OCF1A R/W 0
3 OCF1B R/W 0
2 TOV1 R/W 0
1 OCF0 R/W 0
0 TOV0 R/W 0 TIFR
* Bit 7 - OCF2: Output Compare Flag 2 The OCF2 bit is set (one) when a Compare Match occurs between the Timer/Counter2 and the data in OCR2 - Output Compare Register2. OCF2 is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, OCF2 is cleared by writing a logic one to the flag. When the I-bit in SREG, and OCIE2 (Timer/Counter2 Compare match Interrupt Enable), and the OCF2 are set (one), the Timer/Counter2 Compare match Interrupt is executed. * Bit 6 - TOV2: Timer/Counter2 Overflow Flag The TOV2 bit is set (one) when an overflow occurs in Timer/Counter2. TOV2 is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, TOV2 is cleared by writing a logic one to the flag. When the SREG I-bit, and TOIE2 (Tim er /Counter2 Overf low Interrupt Enabl e), and TO V2 are set (one), the Timer/Counter2 Overflow interrupt is executed. In PWM mode, this bit is set when Timer/Counter2 changes counting direction at $00. * Bit 5 - ICF1: Input Capture Flag 1 The ICF1 bit is set (one) to flag an Input Capture event, indicating that the Timer/Counter1 value has been transferred to the Input Capture Register - ICR1. ICF1 is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, ICF1 is cleared by writing a logic one to the flag. When the I-bit in SREG, and TICIE1 (Timer/Counter1 Input Capture Interrupt Enable), and the ICF1 are set (one), the Timer/Counter1 Capture Interrupt is executed. * Bit 4 - OCF1A: Output Compare Flag 1A The OCF1A bit is set (one) when a Compare Match occurs between the Timer/Counter1 and the data in OCR1A - Output Compare Register 1A. OCF1A is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, OCF1A is cleared by writing a logic one to the flag. When the I-bit in SREG, and OCIE1A (Timer/Counter1 Compare Match Interrupt A Enable), and the OCF1A are set (one), the Timer/Counter1 Compare Match A Interrupt is executed. * Bit 3 - OCF1B: Output Compare Flag 1B The OCF1B bit is set (one) when a Compare Match occurs between the Timer/Counter1 and the data in OCR1B - Output Compare Register 1B. OCF1B is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, OCF1B is cleared by writing a logic one to the flag. When the I-bit in SREG, and OCIE1B (Timer/Counter1 Compare Match Interrupt B Enable), and the OCF1B are set (one), the Timer/Counter1 Compare Match B Interrupt is executed.
36
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
* Bit 2 - TOV1: Timer/Counter1 Overflow Flag The TOV1 is set (one) when an overflow occurs in Timer/Counter1. TOV1 is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, TOV1 is cleared by writing a logic one to the flag. When the I-bit in SREG, and TOIE1 (Tim er /Counter1 Overf low Interrupt Enabl e), and TO V1 are set (one), the Timer/Counter1 Overflow Interrupt is executed. In PWM mode, this bit is set when Timer/Counter1 changes counting direction at $0000. * Bit 1- OCF0: Output Compare Flag 0 The OCF0 bit is set (one) when a Compare Match occurs between the Timer/Counter0 and the data in OCR0 - Output Compare Register 0. OCF0 is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, OCF0 is cleared by writing a logic one to the flag. When the I-bit in SREG, and OCIE0 (Timer/Counter0 Compare Match Interrupt Enable), and the OCF0 are set (one), the Timer/Counter0 Compare Match Interrupt is executed. * Bit 0 - TOV0: Timer/Counter0 Overflow Flag The bit TOV0 is set (one) when an overflow occurs in Timer/Counter0. TOV0 is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, TOV0 is cleared by writing a logic one to the flag. When the SREG I-bit, and TOIE0 (Tim er /Counter0 Overf low Interrupt Enabl e), and TO V0 are set (one), the Timer/Counter0 Overflow interrupt is executed. In PWM mode, this bit is set when Timer/Counter0 changes counting direction at $00. External Interrupts The External Interrupts are triggered by the INT0, INT1, and INT2 pins. Observe that, if enabled, the interrupts will trigger even if the INT0..2 pins are configured as outputs. This feature provides a way of generating a software interrupt. The External Interrupts can be triggered by a falling or rising edge or a low level (INT2 is only an edge triggered interrupt). This is set up as indicated in the specification for the MCU Control Register - MCUCR and MCU Control and Status Register - MCUCSR. When the External Interrupt is enabled and is configured as level triggered (only INT0/INT1), the interrupt will trigger as long as the pin is held low. The MCU Control Register contains control bits for general MCU functions.
Bit $37 ($57) Read/Write Initial Value 7 SE R/W 0 6 SM2 R/W 0 5 SM1 R/W 0 4 SM0 R/W 0 3 ISC11 R/W 0 2 ISC10 R/W 0 1 ISC01 R/W 0 0 ISC00 R/W 0 MCUCR
MCU Control Register - MCUCR
* Bit 7 - SE: Sleep Enable The SE bit must be set (one) to make the MCU enter the sleep mode when the SLEEP instruction is executed. To avoid the MCU entering the sleep mode unless it is the programmers purpose, it is recommended to set the Sleep Enable (SE) bit just before the execution of the SLEEP instruction.
37
1457G-AVR-09/03
* Bits 6..4 - SM2..0: Sleep Mode Select Bits 2, 1 and 0 These bits select between the six available sleep modes as shown in Table 8. Table 8. Sleep Mode Select
SM2 0 0 0 0 1 1 1 1 Note: SM1 0 0 1 1 0 0 1 1 SM0 0 1 0 1 0 1 0 1 Sleep Mode Idle ADC Noise Reduction Power-down Power-save Reserved Reserved Standby(1) Extended Standby(1)
1. Standby mode and Extended Standby mode are only available with external crystals or resonators.
* Bits 3, 2 - ISC11, ISC10: Interrupt Sense Control 1 Bit 1 and Bit 0 The External Interrupt 1 is activated by the external pin INT1 if the SREG I-flag and the corresponding interrupt mask in the GICR are set. The level and edges on the external INT1 pin that activate the interrupt are defined in Table 9. The value on the INT1 pin is sampled before detecting edges. If edge or toggle interrupt is selected, pulses that last longer than one clock period will generate an interrupt. Shorter pulses are not guaranteed to generate an interrupt. If low level interrupt is selected, the low level must be held until the completion of the currently executing instruction to generate an interrupt. Table 9. Interrupt 1 Sense Control
ISC11 0 0 1 1 ISC10 0 1 0 1 Description The low level of INT1 generates an interrupt request. Any logical change on INT1 generates an interrupt request. The falling edge of INT1 generates an interrupt request. The rising edge of INT1 generates an interrupt request.
* Bit 1, 0 - ISC01, ISC00: Interrupt Sense Control 0 Bit 1 and Bit 0 The External Interrupt 0 is activated by the external pin INT0 if the SREG I-flag and the corresponding interrupt mask are set. The level and edges on the external INT0 pin that activate the interrupt are defined in Table 10. The value on the INT0 pin is sampled before detecting edges. If edge or toggle interrupt is selected, pulses that last longer than one clock period will generate an interrupt. Shorter pulses are not guaranteed to generate an interrupt. If low level interrupt is selected, the low level must be held until the completion of the currently executing instruction to generate an interrupt.
38
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Table 10. Interrupt 0 Sense Control
ISC01 0 0 1 1 ISC00 0 1 0 1 Description The low level of INT0 generates an interrupt request. Any logical change on INT0 generates an interrupt request. The falling edge of INT0 generates an interrupt request. The rising edge of INT0 generates an interrupt request.
Sleep Modes
To enter any of the six sleep modes, the SE bit in MCUCR must be set (one) and a SLEEP instruction must be executed. The SM2, SM1, and SM0 bits in the MCUCR Register select which sleep mode (Idle, ADC Noise Reduction, Power-down, Power-save, Standby or Extended Standby) will be activated by the SLEEP instruction. See Table 8 for a summary. If an enabled interrupt occurs while the MCU is in a sleep mode, the MCU wakes up. The MCU is then halted for four cycles, executes the interrupt routine, and resumes execution from the instruction following SLEEP. The contents of the Register File, SRAM, and I/O Memory are unaltered when the device wakes up from sleep. If a reset occurs during sleep mode, the MCU wakes up and executes from the Reset Vector. When the SM2..0 bits are set to 000, the SLEEP instruction makes the MCU enter Idle mode, stopping the CPU but allowing SPI, USART, Analog Comparator, ADC, Two-wire Serial Interface, Timer/Counters, Watchdog, and the interrupt system to continue operating. This enables the MCU to wake up from external triggered interrupts as well as internal ones like the Timer Overflow and USART Transmit Complete interrupts. If wake-up from the Analog Comparator interrupt is not required, the Analog Comparator can be powered down by setting the ACD-bit in the Analog Comparator Control and Status Register - ACSR. This will reduce power consumption in Idle mode. If the ADC is enabled, a conversion starts automatically when this mode is entered. When the SM2..0 bits are set to 001, the SLEEP instruction makes the MCU enter ADC Noise Reduction mode, stopping the MCU but allowing the ADC, the external interrupts, the Two-wire Serial Interface address watch, Timer/Counter2 and the Watchdog to continue operating (if enabled). This improves the noise environment for the ADC, enabling higher resolution measurements. If the ADC is enabled, a conversion starts automatically when this mode is entered. Apart form the ADC Conversion Complete interrupt, only an External Reset, a Watchdog Reset, a Brown-out Reset, a Two-wire Serial Interface address match interrupt, or an external level interrupt on INT0 or INT1, or an external edge interrupt on INT2, can wake up the MCU from ADC Noise Reduction mode. A Timer/Counter2 Output Compare or overflow event will wake up the MCU, but will not generate an interrupt unless Timer/Counter2 is clocked asynchronously. In future devices this is subject to change. It is recommended for future code compatibility to disable Timer/Counter2 interrupts during ADC Noise Reduction mode if the Timer/Counter2 is clocked synchronously.
Idle Mode
ADC Noise Reduction Mode
39
1457G-AVR-09/03
Power-down Mode
When the SM2..0 bits are 010, the SLEEP instruction makes the MCU enter Powerdown mode. In this mode, the external Oscillator is stopped, while the external interrupts, the Two-wire Serial Interface address watch, and the Watchdog continue operating (if enabled). Only an External Reset, a Watchdog Reset, an Two-wire Serial Interface address match interrupt, an external level interrupt on INT0 or INT1, or an external edge interrupt on INT2 can wake up the MCU. Note that if a level triggered interrupt is used for wake-up from Power-down mode, the changed level must be held for some time to wake up the MCU. This makes the MCU less sensitive to noise. The changed level is sampled twice by the Watchdog Oscillator clock, and if the input has the required level during this time, the MCU will wake up. The period of the Watchdog Oscillator is 1 s (nominal) at 5.0V and 25C. The frequency of the Watchdog Oscillator is voltage dependent as shown in the Electrical Characteristics section. When waking up from Power-down mode, there is a delay from the wake-up condition occurs until the wake-up becomes effective. This allows the clock to restart and become stable after having been stopped. The wake-up period is defined by the same CKSEL Fuses that define the Reset Time-out Period, as seen in Table 6 on page 27.
Power-save Mode
When the SM2..0 bits are 011, the SLEEP instruction forces the MCU into the Powersave mode. This mode is identical to Power-down, with one exception: If Timer/Counter2 is clocked asynchronously, i.e., the AS2 bit in ASSR is set, Timer/Counter2 will run during sleep. The device can wake up from either Timer Overf lo w o r Ou tp ut Co mp are e v ent f r om Ti m er/ Cou nt er2 i f t he correspo ndi ng Timer/Counter2 interrupt enable bits are set in TIMSK, and the Global Interrupt Enable bit in SREG is set. If the asynchronous timer is NOT clocked asynchronously, Power-down mode is recommended instead of Power-save mode because the contents of the registers in the asynchronous timer should be considered undefined after wake-up in Power-save mode if AS2 is 0.
Standby Mode
When the SM2..0 bits are 110 and an external crystal/resonator clock option is selected, the SLEEP instruction forces the MCU into the Standby mode. This mode is identical to Power-down with the exception that the Oscillator is kept running. From Standby mode, the device wakes up in only six clock cycles. When the SM2..0 bits are 111 and an external crystal/resonator clock option is selected, the SLEEP instruction forces the MCU into the Extended Standby mode. This mode is identical to Power-save mode with the exception that the Oscillator is kept running. From Extended Standby mode, the device wakes up in only six clock cycles.
Extended Standby Mode
40
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Calibrated Internal RC Oscillator
The calibrated internal Oscillator provides a fixed 1.0 MHz (nominal) clock at 5V and 25C. This clock may be used as the system clock. See the section "Clock Options" on page 6 for information on how to select this clock as the system clock. This Oscillator can be calibrated by writing the calibration byte to the OSCCAL Register. When this Oscillator is used as the chip clock, the Watchdog Oscillator will still be used for the Watchdog Timer and for the Reset Time-out. For details on how to use the pre-programmed calibration value, see the section "Calibration Byte" on page 188.
Oscillator Calibration Register - OSCCAL
Bit $31 ($51) Read/Write Initial Value
7 CAL7 R/W 0
6 CAL6 R/W 0
5 CAL5 R/W 0
4 CAL4 R/W 0
3 CAL3 R/W 0
2 CAL2 R/W 0
1 CAL1 R/W 0
0 CAL0 R/W 0 OSCCAL
* Bits 7..0 - CAL7..0: Oscillator Calibration Value Writing the calibration byte to this address will trim the internal Oscillator to remove process variations from the Oscillator frequency. When OSCCAL is zero, the lowest available frequency is chosen. Writing non-zero values to this register will increase the frequency of the internal Oscillator. Writing $FF to the register gives the highest available frequency. The calibrated Oscillator is used to time EEPROM and Flash access. If EEPROM or Flash is written, do not calibrate to more than 10% above the nominal frequency. Otherwise, the EEPROM or Flash write may fail. Note that the Oscillator is intended for calibration to 1.0 MHz, thus tuning to other values is not guaranteed. Table 11. Internal RC Oscillator Frequency Range
OSCCAL Value $00 $7F $FF Min Frequency (MHz) 0.5 0.7 1.0 Max Frequency (MHz) 1.0 1.5 2.0
Special Function IO Register - SFIOR
Bit $30 ($50) Read/Write Initial Value
7 - R 0
6 - R 0
5 - R 0
4 - R 0
3 ACME R/W 0
2 PUD R/W 0
1 PSR2 R/W 0
0 PSR10 R/W 0 SFIOR
* Bit 7..4 - Res: Reserved Bits These bits are reserved bits in the ATmega323 and always read as zero. * Bit 3 - ACME: Analog Comparator Multiplexer Enable When this bit is set (one) and the ADC is switched off (ADEN in ADCSR is zero), the ADC multiplexer selects the negative input to the Analog Comparator. When this bit is cleared (zero), AIN1 is applied to the negative input of the Analog Comparator. For a detailed description of this bit, see "Analog Comparator Multiplexed Input" on page 126. * Bit 2 - PUD: Pull-up Disable When this bit is set (one), all pull-ups on all ports are disabled. If the bit is cleared (zero), the pull-ups can be individually enabled as described in the chapter "I/O Ports" on page 137.
41
1457G-AVR-09/03
* Bit 1 - PSR2: Prescaler Reset Timer/Counter2 When this bit is set (one) the Timer/Counter2 prescaler will be reset. The bit will be cleared by hardware after the operation is performed. Writing a zero to this bit will have no effect. This bit will always be read as zero if Timer/Counter2 is clocked by the internal CPU clock. If this bit is written when Timer/Counter2 is operating in asynchronous mode, the bit will remain one until the prescaler has been reset. See "Asynchronous Operation of Timer/Counter2" on page 53 for a detailed description of asynchronous operation. * Bit 0 - PSR10: Prescaler Reset Timer/Counter1 and Timer/Counter0 When this bit is set (one) the Timer/Counter1 and Timer/Counter0 prescaler will be reset. The bit will be cleared by hardware after the operation is performed. Writing a zero to this bit will have no effect. Note that Timer/Counter1 and Timer/Counter0 share the same prescaler and a reset of this prescaler will affect both timers. This bit will always be read as zero.
42
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Timer/Counters
The ATmega323 provides three general purpose Timer/Counters - two 8-bit T/Cs and one 16-bit T/C. Timer/Counter2 can optionally be asynchronously clocked from an external Oscillator. This Oscillator is optimized for use with a 32.768 kHz watch crystal, enabling use of Timer/Counter2 as a Real Time Counter (RTC). Timer/Counters 0 and 1 have individual prescaling selection from the same 10-bit prescaler. Timer/Counter2 has its own prescaler. Both these prescalers can be reset by setting the corresponding control bits in the Special Functions IO Register (SFIOR). These Timer/Counters can either be used as a timer with an internal clock time-base or as a counter with an external pin connection which triggers the counting. Figure 30. Prescaler for Timer/Counter0 and Timer/Counter1
Clear
Timer/Counter Prescalers
PSR10
TCK1
TCK0
For Timer/Counters 0 and 1, the four different prescaled selections are: CK/8, CK/64, CK/256, and CK/1024, where CK is the Oscillator clock. For the two Timer/Counters0 and 1, CK, external source, and stop can also be selected as clock sources. Setting the PSR10 bit in SFIOR Resets the prescaler. This allows the user to operate with a predictable prescaler. Note that Timer/Counter1 and Timer/Counter0 share the same prescaler and a Prescaler Reset will affect both Timer/Counters.
43
1457G-AVR-09/03
Figure 31. Prescaler for Timer/Counter2
CK XTAL1
PCK2 Clear
PCK2/8
10-BIT T/C PRESCALER
PCK2/32 PCK2/64 PCK2/1024
1457G-AVR-09/03
AS2
PSR2
0
CS20 CS21 CS22
TIMER/COUNTER2 CLOCK SOURCE TCK2
The clock source for Timer/Counter2 is named PCK2. PCK2 is by default connected to the main system clock CK. By setting the AS2 bit in ASSR, Timer/Counter2 is asynchronously clocked from the PC6(TOSC1) pin. This enables use of Timer/Counter2 as a Real Time Counter (RTC). When AS2 is set, pins PC6(TOSC1) and PC7(TOSC2) are disconnected from Port C. A crystal can then be connected between the PC6(TOSC1) and PC7(TOSC2) pins to serve as an independent clock source for Timer/Counter2. The Oscillator is optimized for use with a 32.768 kHz crystal. Applying an external clock source to TOSC1 is not recommended. Setting the PSR2 bit in SFIOR resets the prescaler. This allows the user to operate with a predictable prescaler.
44
ATmega323(L)
PCK2/128
PCK2/256
ATmega323(L)
8-bit Timers/Counters Timer/Counter0 and Timer/Counter2
Figure 32 shows the block diagram for Timer/Counter0. Figure 33 shows the block diagram for Timer/Counter2. Figure 32. Timer/Counter0 Block Diagram
T/C0 COMPARE T/C0 OVERFLOW IRQ MATCH IRQ
OCIE1A
OCIE1B
TICIE1
OCIE2
OCIE0
TOIE2
TOIE1
TOIE0
OCF0
8-BIT DATA BUS
TIMER INT. MASK REGISTER (TIMSK)
OCF2
TIMER INT. FLAG REGISTER (TIFR)
FOC0 OCF1A OCF1B TOV2 ICF1 OCF0 TOV1 TOV0
TOV0
T/C0 CONTROL REGISTER (TCCR0)
COM01 COM00 CTC0 PWM0 CS02 CS01 CS00
SPECIAL FUNCTIONS IO REGISTER (SFIOR)
PSR10 PSR2
7 TIMER/COUNTER0 (TCNT0)
0
T/C CLEAR T/C CLK SOURCE UP/DOWN
CONTROL LOGIC
CK
T0
7 8-BIT COMPARATOR
0
7 OUTPUT COMPARE REGISTER0 (OCR0)
0
45
1457G-AVR-09/03
Figure 33. Timer/Counter2 Block Diagram
T/C2 OVER- T/C2 COMPARE FLOW IRQ MATCH IRQ
8-BIT DATA BUS 8-BIT ASYNCH T/C2 DATA BUS
OCIE1A
OCIE2
TICIE1
OCIE1B
OCIE0
TOIE2
TOIE1
TOIE0
OCF2
TOV2
TIMER INT. MASK REGISTER (TIMSK)
OCF2
TIMER INT. FLAG REGISTER (TIFR)
FOC2 TOV2 OCF1A OCF1B OCF0 TOV1 TOV0 ICF1
T/C2 CONTROL REGISTER (TCCR2)
COM21 COM20 PWM2 CTC2 CS22 CS21 CS20
SPECIAL FUNCTIONS IO REGISTER (SFIOR)
PSR10 PSR2
7 TIMER/COUNTER2 (TCNT2)
0
T/C CLEAR T/C CLK SOURCE UP/DOWN
CONTROL LOGIC
CK TOSC1
7 8-BIT COMPARATOR
0
7 OUTPUT COMPARE REGISTER2 (OCR2)
0 ASYNCH. STATUS REGISTER (ASSR)
AS2 OCR2UB ICR2UB TC2UB
CK PCK2
SYNCH UNIT
The 8-bit Timer/Counter0 can select clock source from CK, prescaled CK, or an external pin. The 8-bit Timer/Counter2 can select clock source from CK, prescaled CK, external TOSC1 or prescaled external TOSC1. Both Timers/Counters can be stopped as described in section "Timer/Counter0 Control Register - TCCR0" on page 47 and "Bit 7 - FOC0/FOC2: Force Output Compare" on page 47. The various Status Flags (Overflow and Compare Matc h) are f ound in the Timer/Counter Interrupt Flag Register - TIFR (see page 36). Control signals are found in the Timer/Counter Control Register - TCCR0 and TCCR2. The interrupt enable/disable settings are found in the Timer/Counter Interrupt Mask Register - TIMSK (see page 34). When Timer/Counter0 is externally clocked, the external signal is synchronized with the Oscillator frequency of the CPU. To assure proper sampling of the external clock, the minimum time between two external clock transitions must be at least one internal CPU clock period. The external clock signal is sampled on the rising edge of the internal CPU clock. The 8-bit Timer/Counters feature both a high-resolution and a high-accuracy usage with the lower prescaling opportunities. Similarly, the high-prescaling opportunities make the Timer/Counter0 useful for lower speed functions or exact timing functions with infrequent actions.
46
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Timer/Counter0 and 2 can also be used as 8-bit Pulse Width Modulators. In this mode, the Timer/Counter and the Output Compare Register serve as a glitch-free, stand-alone PWM with centered pulses. Refer to page 49 for a detailed description on this function. Timer/Counter0 Control Register - TCCR0
Bit $33 ($53) Read/Write Initial Value
7 FOC0 R/W 0
6 PWM0 R/W 0
5 COM01 R/W 0
4 COM00 R/W 0
3 CTC0 R/W 0
2 CS02 R/W 0
1 CS01 R/W 0
0 CS00 R/W 0 TCCR0
Timer/Counter2 Control Register - TCCR2
Bit $25 ($45) Read/Write Initial Value
7 FOC2 R/W 0
6 PWM2 R/W 0
5 COM21 R/W 0
4 COM20 R/W 0
3 CTC2 R/W 0
2 CS22 R/W 0
1 CS21 R/W 0
0 CS20 R/W 0 TCCR2
* Bit 7 - FOC0/FOC2: Force Output Compare Writing a logical one to this bit, forces a change in the Compare Match output pin PB3 (Timer/Counter0) and PD7 (Timer/Counter2) according to the values already set in COMn1 and COMn0. If the COMn1 and COMn0 bits are written in the same cycle as FOC0/FOC2, the new settings will not take effect until next Compare Match or Forced Output Compare Match occurs. The Force Output Compare bit can be used to change the output pin without waiting for a Compare Match in the timer. The automatic action programmed in COMn1 and COMn0 happens as if a Compare Match had occurred, but no interrupt is generated and the Timer/Counters will not be cleared even if CTC0/CTC2 is set. The corresponding I/O pin must be set as an output pin for the FOC0/FOC2 bit to have effect on the pin. The FOC0/FOC2 bits will always be read as zero. Setting the FOC0/FOC2 bits has no effect in PWM mode. * Bit 6 - PWM0/PWM2: Pulse Width Modulator Enable When set (one) this bit enables PWM mode for Timer/Counter0 or Timer/Counter2. This mode is described on page 49. * Bits 5, 4 - COM01, COM00/COM21, COM20: Compare Output Mode, Bits 1 and 0 The COMn1 and COMn0 control bits determine any output pin action following a compare match in Timer/Counter0 or Timer/Counter2. Output pin actions affect pins PB3(OC0) or PD7(OC2). This is an alternative function to an I/O port, and the corresponding direction control bit must be set (one) to control an output pin. The control configuration is shown in Table 12. Table 12. Compare Mode Select(1)
COMn1(2) 0 0 1 1 Notes: COMn0 0 1 0 1 Description Timer/Counter Disconnected from Output Pin OCn Toggle the OCn Output Line. Clear the OCn Output Line (to Zero). Set the OCn Output Line (to One).
1. In PWM mode, these bits have a different function. Refer to Table 15 for a description. 2. n = 0 or 2
47
1457G-AVR-09/03
* Bit 3 - CTC0/CTC2: Clear Timer/Counter on Compare Match When the CTC0 or CTC2 control bit is set (one), Timer/Counter0 or Timer/Counter2 is reset to $00 in the CPU clock cycle following a Compare Match. If the control bit is cleared, the Timer/Counter continues counting and is unaffected by a Compare Match. When a prescaling of 1 is used, and the Compare Register is set to C, the timer will count as follows if CTC0/CTC2 is set: ... | C-1 | C | 0 | 1 | ... When the prescaler is set to divide by 8, the timer will count like this: ... | C-1, C-1, C-1, C-1, C-1, C-1, C-1, C-1 | C, C, C, C, C, C, C, C | 0, 0, 0, 0, 0, 0, 0, 0 | 1, 1, 1, ... In PWM mode, this bit has a different function. If the CTC0 or CTC2 bit is cleared in PWM mode, the Timer/Counter acts as an up/down counter. If the CTC0 or CTC2 bit is set (one), the Timer/Counter wraps when it reaches $FF. Refer to page 49 for a detailed description. * Bits 2, 1, 0 - CS02, CS01, CS00/ CS22, CS21, CS20: Clock Select bits 2, 1, and 0 The Clock Select bits 2, 1, and 0 define the prescaling source of Timer/Counter0 and Timer/Counter2. Table 13. Clock 0 Prescale Select
CS02 0 0 0 0 1 1 1 1 CS01 0 0 1 1 0 0 1 1 CS00 0 1 0 1 0 1 0 1 Description Stop, the Timer/Counter0 is Stopped CK CK/8 CK/64 CK/256 CK/1024 External Pin PB0(T0), Falling Edge External Pin PB0(T0), Rising Edge
Table 14. Clock 2 Prescale Select
CS22 0 0 0 0 1 1 1 1 CS21 0 0 1 1 0 0 1 1 CS20 0 1 0 1 0 1 0 1 Description Stop, the Timer/Counter2 is Stopped PCK2 PCK2/8 PCK2 /32 PCK2/64 PCK2/128 PCK2/256 PCK2/1024
48
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
The Stop condition provides a Timer Enable/Disable function. The prescaled modes are scaled directly from the CK Oscillator clock for Timer/Counter0 and PCK2 for Timer/Counter2. If the external pin modes are used for Timer/Counter0, transitions on PB0(T0) will clock the counter even if the pin is configured as an output. This feature can give the user SW control of the counting. Timer Counter0 - TCNT0
Bit $32 ($52) Read/Write Initial Value 7 MSB R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 6 5 4 3 2 1 0 LSB R/W 0 TCNT0
Timer/Counter2 - TCNT2
Bit $24 ($44) Read/Write Initial Value 7 MSB R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 6 5 4 3 2 1 0 LSB R/W 0 TCNT2
These 8-bit registers contain the value of the Timer/Counters. Both Timer/Counters is realized as up or up/down (in PWM mode) counters with read and write access. If the Timer/Counter is written to and a clock source is selected, it continues counting in the timer clock cycle following the write operation. Timer/Counter0 Output Compare Register - OCR0
Bit $3C ($5C) Read/Write Initial Value
7 MSB R/W 0
6
5
4
3
2
1
0 LSB OCR0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
Timer/Counter2 Output Compare Register - OCR2
Bit $23 ($43) Read/Write Initial Value
7 MSB R/W 0
6
5
4
3
2
1
0 LSB OCR2
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
The Output Compare Registers are 8-bit read/write registers. The Timer/Counter Output Compare Registers contains the data to be continuously compared with the Timer/Counter. Actions on compare matches are specified in TCCR0 and TCCR2. A software write to the Timer/Counter Register blocks compare matches in the next Timer/Counter clock cycle. This prevents immediate interrupts when initializing the Timer/Counter. A Compare Match will set the Compare Interrupt Flag in the CPU clock cycle following the compare event. Timer/Counter 0 and 2 in PWM Mode When PWM mode is selected, the Timer/Counter either wraps (overflows) when it reaches $FF or it acts as an up/down counter. If the up/down mode is selected, the Timer/Counter and the Output Compare Registers - OCR0 or OCR2 form an 8-bit, free running, glitch-free and phase correct PWM with outputs on the PB3(OC0/PWM0) or PD7(OC2/PWM2) pin. If the overflow mode is selected, the Timer/Counter and the Output Compare Registers - OCR0 or OCR2 form an 8-bit, free running and glitch-free PWM, operating with twice the speed of the up/down counting mode. 49
1457G-AVR-09/03
PWM Modes (Up/Down and Overflow)
The two different PWM modes are selected by the CTC0 or CTC2 bit in the Timer/Counter Control Registers -TCCR0 or TCCR2 respectively. If CTC0/CTC2 is cleared and PWM mode is selected, the Timer/Counter acts as an up/down counter, counting up from $00 to $FF, where it turns and counts down again to zero before the cycle is repeated. When the counter value matches the contents of the Output Compare Register, the PB3(OC0/PWM0) or PD7(OC2/PWM2) pin is set or cleared according to the settings of the COMn1/COMn0 bits in the Timer/Counter Control Registers TCCR0 or TCCR2. If CTC0/CTC2 is set and PWM mode is selected, the Timer/Counters will wrap and start counting from $00 after reaching $FF. The PB3(OC0/PWM0) or PD7(OC2/PWM2) pin will be set or cleared according to the settings of COMn1/COMn0 on a Timer/Counter overflow or when the counter value matches the contents of the Output Compare Register. Refer to Table 15 for details. Table 15. Compare Mode Select in PWM Mode(1)
CTCn 0 0 0 COMn1 0 0 1 COMn0 0 1 0 Effect on Compare Pin Not connected Not connected Cleared on Compare Match, up-counting. Set on Compare Match, down-counting (non-inverted PWM) Cleared on Compare Match, down-counting. Set on Compare Match, up-counting (inverted PWM) Not connected Not connected Cleared on Compare Match, set on overflow Set on Compare Match, cleared on overflow fTCK0/2/256 fTCK0/2/256 fTCK0/2/510 Frequency
0 1 1 1 1 Note:
1 0 0 1 1 1. n = 0 or 2
1 0 1 0 1
fTCK0/2/510
Note that in PWM mode, the value to be written to the Output Compare Register is first transferred to a temporary location, and then latched into the OCR when the Timer/Counter reaches $FF. This prevents the occurrence of odd-length PWM pulses (glitches) in the event of an unsynchronized OCR0 or OCR2 write. See Figure 34 and Figure 35 for examples.
50
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Figure 34. Effects of Unsynchronized OCR Latching in Up/Down Mode
Compare Value changes Counter Value Compare Value PWM Output OCn Synchronized OCn Latch Compare Value changes Counter Value Compare Value PWM Output OCn Unsynchronized OCn Latch Glitch
Figure 35. Effects of Unsynchronized OCR Latching in Overflow Mode
Compare Value changes Counter Value Compare Value PWM Output OCn Synchronized OCn Latch Compare Value changes Counter Value Compare Value PWM Output OCn Unsynchronized OCn Latch
Note: n = 0 or 2 (Figure 34 and Figure 35).
Glitch
During the time between the write and the latch operation, a read from the Output Compare Registers will read the contents of the temporary location. This means that the most recently written value always will read out of OCR0 and OCR2. When the Output Compare Register contains $00 or $FF, and the up/down PWM mode is selected, the output PB3(OC0/PWM0)/PD7(OC2/PWM2) is updated to low or high on the next compare match according to the settings of COMn1/COMn0. This is shown in Table 16. In overflow PWM mode, the output PB3(OC0/PWM0)/PD7(OC2/PWM2) is held low or high only when the Output Compare Register contains $FF.
51
1457G-AVR-09/03
Table 16. PWM Outputs OCRn = $00 or $FF(1)
COMn1 1 1 1 1 Note: COMn0 0 0 1 1 OCRn $00 $FF $00 $FF Output PWMn L H H L
1. n = 0 or 2 In overflow PWM mode, the table above is only valid for OCRn = $FF.
In up/down PWM mode, the Timer Overflow Flag, TOV0 or TOV2, is set when the counter advances from $00. In overflow PWM mode, the Timer Overflow Flag is set as in normal Timer/Counter mode. Timer Overflow Interrupt0 and 2 operate exactly as in normal Timer/Counter mode, i.e., they are executed when TOV0 or TOV2 are set provided that Timer Overflow Interrupt and Global Interrupts are enabled. This does also apply to the Timer Output Compare Flag and interrupt. Asynchronous Status Register - ASSR
Bit $22 ($22) Read/Write Initial Value
7 - R 0
6 - R 0
5 - R 0
4 - R 0
3 AS2 R/W 0
2 TCN2UB R 0
1 OCR2UB R 0
0 TCR2UB R 0 ASSR
* Bit 7..4 - Res: Reserved Bits These bits are reserved bits in the ATmega323 and always read as zero. * Bit 3 - AS2: Asynchronous Timer/Counter2 When AS2 is cleared (zero), Timer/Counter2 is clocked from the internal system clock, CK. When AS2 is set (one), Timer/Counter2 is clocked from the TOSC1 pin. Pins PC6 and PC7 are connected to a crystal Oscillator and cannot be used as general I/O pins. When the value of this bit is changed, the contents of TCNT2, OCR2, and TCCR2 might be corrupted. * Bit 2 - TCN2UB: Timer/Counter2 Update Busy When Timer/Counter2 operates asynchronously and TCNT2 is written, this bit becomes set (one). When TCNT2 has been updated from the temporary storage register, this bit is cleared (zero) by hardware. A logical zero in this bit indicates that TCNT2 is ready to be updated with a new value. * Bit 1 - OCR2UB: Output Compare Register2 Update Busy When Timer/Counter2 operates asynchronously and OCR2 is written, this bit becomes set (one). When OCR2 has been updated from the temporary storage register, this bit is cleared (zero) by hardware. A logical zero in this bit indicates that OCR2 is ready to be updated with a new value. * Bit 0 - TCR2UB: Timer/Counter Control Register2 Update Busy When Timer/Counter2 operates asynchronously and TCCR2 is written, this bit becomes set (one). When TCCR2 has been updated from the temporary storage register, this bit is cleared (zero) by hardware. A logical zero in this bit indicates that TCCR2 is ready to be updated with a new value. 52
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
If a write is performed to any of the three Timer/Counter2 Registers while its Update Busy Flag is set (one), the updated value might get corrupted and cause an unintentional interrupt to occur. The mechanisms for reading TCNT2, OCR2, and TCCR2 are different. When reading TCNT2, the actual timer value is read. When reading OCR2 or TCCR2, the value in the temporary storage register is read. Asynchronous Operation of Timer/Counter2 When Timer/Counter2 operates asynchronously, some considerations must be taken. Warning: When switching between asynchronous and synchronous clocking of Timer/Counter2, the Timer Registers TCNT2, OCR2, and TCCR2 might be corrupted. A safe procedure for switching clock source is: 1. Disable the Timer/Counter2 interrupts by clearing OCIE2 and TOIE2. 2. Select clock source by setting AS2 as appropriate. 3. Write new values to TCNT2, OCR2, and TCCR2. 4. To switch to asynchronous operation: Wait for TCN2UB, OCR2UB, and TCR2UB. 5. Clear the Timer/Counter2 Interrupt Flags. 6. Enable interrupts, if needed. The Oscillator is optimized for use with a 32.768 kHz watch crystal. Applying an external clock to the TOSC1 pin may result in incorrect Timer/Counter2 operation. The CPU main clock frequency must be more than four times the Oscillator frequency. When writing to one of the registers TCNT2, OCR2, or TCCR2, the value is transferred to a temporary register, and latched after two positive edges on TOSC1. The user should not write a new value before the contents of the temporary register have been transferred to its destination. Each of the three mentioned registers have their individual temporary register, which means that e.g. writing to TCNT2 does not disturb an OCR2 write in progress. To detect that a transfer to the destination register has taken place, the Asynchronous Status Register - ASSR has been implemented. When entering Power-save or Extended Standby mode after having written to TCNT2, OCR2, or TCCR2, the user must wait until the written register has been updated if Timer/Counter2 is used to wake up the device. Otherwise, the MCU will enter sleep mode before the changes are effective. This is particularly important if the Output Compare2 Interrupt is used to wake up the device, since the Output Compare function is disabled during writing to OCR2 or TCNT2. If the write cycle is not finished, and the MCU enters sleep mode before the OCR2UB bit returns to zero, the device will never receive a compare match interrupt, and the MCU will not wake up. If Timer/Counter2 is used to wake the device up from Power-save or Extended Standby mode, precautions must be taken if the user wants to re-enter one of these modes: The interrupt logic needs one TOSC1 cycle to be reset. If the time between wake-up and reentering sleep mode is less than one TOSC1 cycle, the interrupt will not occur, and the device will fail to wake up. If the user is in doubt whether the time before re-entering Power-save or Extended Standby mode is sufficient, the following algorithm can be used to ensure that one TOSC1 cycle has elapsed: 1. Write a value to TCCR2, TCNT2 or OCR2. 2. Wait until the corresponding Update Busy Flag in ASSR returns to zero. 3. Enter Power-save or Extended Standby mode. When the asynchronous operation is selected, the 32.768 kHZ Oscillator for Timer/Counter2 is always running, except in Power-down and Standby modes. After a
53
1457G-AVR-09/03
Power-up Reset or wake-up from Power-down or Standby mode, the user should be aware of the fact that this Oscillator might take as long as one second to stabilize. The user is advised to wait for at least one second before using Timer/Counter2 after Powerup or wake-up from Power-down or Standby mode. The contents of all Timer/Counter2 Registers must be considered lost after a wake-up from Power-down or Standby mode due to unstable clock signal upon start-up, no matter whether the Oscillator is in use or a clock signal is applied to the TOSC1 pin. Description of wake up from Power-save or Extended Standby mode when the timer is clocked asynchronously: When the interrupt condition is met, the wake up process is started on the following cycle of the timer clock, that is, the timer is always advanced by at least one before the processor can read the counter value. After wake-up, the MCU is halted for four cycles, it executes the interrupt routine, and resumes execution from the instruction following SLEEP. During asynchronous operation, the synchronization of the Interrupt Flags for the asynchronous timer takes three processor cycles plus one timer cycle. The timer is therefore advanced by at least one before the processor can read the timer value causing the setting of the Interrupt Flag. The Output Compare Pin is changed on the timer clock and is not synchronized to the processor clock.
16-bit Timer/Counter1
Figure 36 shows the block diagram for Timer/Counter1. Figure 36. Timer/Counter1 Block Diagram
T/C1 OVERFLOW IRQ T/C1 COMPARE MATCH A IRQ T/C1 COMPARE T/C1 INPUT MATCH B IRQ CAPTURE IRQ
8-BIT DATA BUS
OCIE1B
OCIE1A
OCF1B
OCF1A
OCIE2
TICIE1
OCIE0
TOIE2
TOIE1
TOIE0
OCF2
OCF0
TOV2
TIMER INT. MASK REGISTER (TIMSK)
TIMER INT. FLAG REGISTER (TIFR)
OCF1B OCF1A ICF1 TOV1
TOV1
ICF1
TOV0
T/C1 CONTROL REGISTER A (TCCR1A)
FOC1B PWM11 COM1A1 COM1B1 PWM10 COM1A0 COM1B0 FOC1A
T/C1 CONTROL REGISTER B (TCCR1B)
ICNC1 CTC1 CS12 ICES1 CS10 CS11
15
87 T/C1 INPUT CAPTURE REGISTER (ICR1)
0 CONTROL LOGIC PSR10 CK T1
CAPTURE TRIGGER
15
87 TIMER/COUNTER1 (TCNT1)
0
T/C CLEAR T/C CLOCK SOURCE UP/DOWN
15
8
7
0
15
8
7
0
16 BIT COMPARATOR
16 BIT COMPARATOR
15
8
7
0
15
8
7
0
TIMER/COUNTER1 OUTPUT COMPARE REGISTER A
TIMER/COUNTER1 OUTPUT COMPARE REGISTER B
The 16-bit Timer/Counter1 can select clock source from CK, prescaled CK, or an external pin. In addition it can be stopped as described in section "Timer/Counter1 Control 54
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Register B - TCCR1B" on page 57. The different Status Flags (Overflow, Compare Match, and Capture Event) are found in the Timer/Counter Interrupt Flag Register - TIFR. Control signals are found in the Timer/Counter1 Control Registers - TCCR1A and TCCR1B. The interrupt enable/disable settings for Timer/Counter1 are found in the Timer/Counter Interrupt Mask Register - TIMSK. When Timer/Counter1 is externally clocked, the external signal is synchronized with the Oscillator frequency of the CPU. To assure proper sampling of the external clock, the minimum time between two external clock transitions must be at least one internal CPU clock period. The external clock signal is sampled on the rising edge of the internal CPU clock. The 16-bit Timer/Counter1 features both a high-resolution and a high-accuracy usage with the lower prescaling opportunities. Similarly, the high-prescaling opportunities makes the Timer/Counter1 useful for lower speed functions or exact timing functions with infrequent actions. The Timer/Counter1 supports two Output Compare functions using the Output Compare Register 1 A and B (OCR1A and OCR1B) as the data sources to be compared to the Timer/Counter1 contents. The Output Compare functions include optional clearing of the counter on compareA match, and actions on the Output Compare Pins on both compare matches. Timer/Counter1 can also be used as an 8-, 9-, or 10-bit Pulse Width Modulator. In this mode the counter and the OCR1A/OCR1B Registers serve as a dual glitch-free standalone PWM with centered pulses. Alternatively, the Timer/Counter1 can be configured to operate at twice the speed in PWM mode, but without centered pulses. Refer to page 60 for a detailed description of this function. The Input Capture function of Timer/Counter1 provides a capture of the Timer/Counter1 contents to the Input Capture Register - ICR1, triggered by an external event on the Input Capture Pin - ICP. The actual capture event settings are defined by the Timer/Counter1 Control Register - TCCR1B. In addition, the Analog Comparator can be set to trigger the Input Capture. Refer to the section, "The Analog Comparator", for details on this. The ICP pin logic is shown in Figure 37. Figure 37. ICP Pin Schematic Diagram
If the noise canceler function is enabled, the actual trigger condition for the capture event is monitored over four samples, and all four must be equal to activate the Capture Flag.
55
1457G-AVR-09/03
Timer/Counter1 Control Register A - TCCR1A
Bit $2F ($4F) Read/Write Initial Value
7 COM1A1 R/W 0
6 COM1A0 R/W 0
5 COM1B1 R/W 0
4 COM1B0 R/W 0
3 FOC1A R/W 0
2 FOC1B R/W 0
1 PWM11 R/W 0
0 PWM10 R/W 0 TCCR1A
* Bits 7, 6 - COM1A1, COM1A0: Compare Output Mode1A, Bits 1 and 0 The COM1A1 and COM1A0 control bits determine any output pin action following a Compare Match in Timer/Counter1. Any output pin actions affect pin OC1A - Output Compare A. This is an alternative function to an I/O port, and the corresponding direction control bit must be set (one) to control an output pin. The control configuration is shown in Table 10. * Bits 5, 4 - COM1B1, COM1B0: Compare Output Mode1B, Bits 1 and 0 The COM1B1 and COM1B0 control bits determine any output pin action following a Compare Match in Timer/Counter1. Any output pin actions affect pin OC1B - Output Compare B. This is an alternative function to an I/O port, and the corresponding direction control bit must be set (one) to control an output pin. The control configuration is shown in Table 10. Table 17. Compare 1 Mode Select(1)
COM1X1 0 0 1 1 Note: 1. X = A or B. COM1X0 0 1 0 1 Description Timer/Counter1 Disconnected from Output Pin OC1X Toggle the OC1X Output Line. Clear the OC1X Output Line (to Zero). Set the OC1X Output Line (to One).
In PWM mode, these bits have a different function. Refer to Table 22 for a description. * Bit 3 - FOC1A: Force Output Compare 1A Writing a logical one to this bit, forces a change in the Compare Match output pin PD5 according to the values already set in COM1A1 and COM1A0. If the COM1A1 and COM1A0 bits are written in the same cycle as FOC1A, the new settings will not take effect until next Compare Match or Forced Compare Match occurs. The Force Output Compare bit can be used to change the output pin without waiting for a Compare Match in the timer. The automatic action programmed in COM1A1 and COM1A0 happens as if a Compare Match had occurred, but no interrupt is generated and it will not clear the timer even if CTC1 in TCCR1B is set. The corresponding I/O pin must be set as an output pin for the FOC1A bit to have effect on the pin. The FOC1A bit will always be read as zero. The setting of the FOC1A bit has no effect in PWM mode. * Bit 2 - FOC1B: Force Output Compare 1B Writing a logical one to this bit, forces a change in the Compare Match output pin PD4 according to the values already set in COM1B1 and COM1B0. If the COM1B1 and COM1B0 bits are written in the same cycle as FOC1B, the new settings will not take effect until next Compare Match or Forced Compare Match occurs. The Force Output Compare bit can be used to change the output pin without waiting for a Compare Match in the timer. The automatic action programmed in COM1B1 and COM1B0 happens as if
56
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
a Compare Match had occurred, but no interrupt is generated. The corresponding I/O pin must be set as an output pin for the FOC1B bit to have effect on the pin. The FOC1B bit will always be read as zero. The setting of the FOC1B bit has no effect in PWM mode. * Bits 1..0 - PWM11, PWM10: Pulse Width Modulator Select Bits These bits select PWM operation of Timer/Counter1 as specified in Table 11. This mode is described on page 60. Table 18. PWM Mode Select
PWM11 0 0 1 1 PWM10 0 1 0 1 Description PWM Operation of Timer/Counter1 is Disabled Timer/Counter1 is an 8-bit PWM Timer/Counter1 is a 9-bit PWM Timer/Counter1 is a 10-bit PWM
Timer/Counter1 Control Register B - TCCR1B
Bit $2E ($4E) Read/Write Initial Value
7 ICNC1 R/W 0
6 ICES1 R/W 0
5 - R 0
4 - R 0
3 CTC1 R/W 0
2 CS12 R/W 0
1 CS11 R/W 0
0 CS10 R/W 0 TCCR1B
* Bit 7 - ICNC1: Input Capture1 Noise Canceler (Four CKs) When the ICNC1 bit is cleared (zero), the Input Capture trigger Noise Canceler function is disabled. The Input Capture is triggered at the first rising/falling edge sampled on the ICP - Input Capture Pin - as specified. When the ICNC1 bit is set (one), four successive samples are measures on the ICP - Input Capture Pin, and all samples must be high/low according to the Input Capture trigger specification in the ICES1 bit. The actual sampling frequency is XTAL clock frequency. * Bit 6 - ICES1: Input Capture1 Edge Select While the ICES1 bit is cleared (zero), the Timer/Counter1 contents are transferred to the Input Capture Register - ICR1 - on the falling edge of the Input Capture Pin - ICP. While the ICES1 bit is set (one), the Timer/Counter1 contents are transferred to the Input Capture Register - ICR1 - on the rising edge of the Input Capture Pin - ICP. * Bits 5, 4 - Res: Reserved bits These bits are reserved bits in the ATmega323 and always read as zero. * Bit 3 - CTC1: Clear Timer/Counter1 on Compare Match When the CTC1 control bit is set (one), the Timer/Counter1 is reset to $0000 in the clock cycle after a Compare A Match. If the CTC1 control bit is cleared, Timer/Counter1 continues counting and is unaffected by a compare match. When a prescaling of one is used, and the Compare A Register is set to C, the timer will count as follows if CTC1 is set: ... | C-1 | C | 0 | 1 |...
57
1457G-AVR-09/03
When the prescaler is set to divide by 8, the timer will count like this: ... | C-1, C-1, C-1, C-1, C-1, C-1, C-1, C-1 | C, C, C, C, C, C, C, C | 0, 0, 0, 0, 0, 0, 0, 0 |1,1,1,1,1,1,1,1|... In PWM mode, this bit has a different function. If the CTC1 bit is cleared in PWM mode, the Timer/Counter1 acts as an up/down counter. If the CTC1 bit is set (one), the Timer/Counter wraps when it reaches the TOP value. Refer to page 60 for a detailed description. * Bits 2..0 - CS12, CS11, CS10: Clock Select1, Bit 2, 1, and 0 The Clock Select1 bits 2, 1, and 0 define the prescaling source of Timer/Counter1. Table 19. Clock 1 Prescale Select
CS12 0 0 0 0 1 1 1 1 CS11 0 0 1 1 0 0 1 1 CS10 0 1 0 1 0 1 0 1 Description Stop, the Timer/Counter1 is Stopped. CK CK/8 CK/64 CK/256 CK/1024 External Pin T1, Falling Edge External Pin T1, Rising Edge
The Stop condition provides a Timer Enable/Disable function. The prescaled modes are scaled directly from the CK Oscillator clock. If the external pin modes are used for Timer/Counter1, transitions on PB1/(T1) will clock the counter even if the pin is configured as an output. This feature can give the user SW control of the counting. Timer/Counter1 - TCNT1H and TCNT1L
Bit $2D ($4D) $2C ($4C)
15 MSB
14
13
12
11
10
9
8 TCNT1H LSB TCNT1L
7 Read/Write R/W R/W Initial Value 0 0
6 R/W R/W 0 0
5 R/W R/W 0 0
4 R/W R/W 0 0
3 R/W R/W 0 0
2 R/W R/W 0 0
1 R/W R/W 0 0
0 R/W R/W 0 0
This 16-bit register contains the prescaled value of the 16-bit Timer/Counter1. To ensure that both the high and Low Bytes are read and written simultaneously when the CPU accesses these registers, the access is performed using an 8-bit temporary register (TEMP). This temporary register is also used when accessing OCR1A, OCR1B, and ICR1. If the main program and also interrupt routines perform access to registers using TEMP, interrupts must be disabled during access from the main program and interrupt routines.
58
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
TCNT1 Timer/Counter1 Write When the CPU writes to the High Byte TCNT1H, the written data is placed in the TEMP Register. Next, when the CPU writes the Low Byte TCNT1L, this byte of data is combined with the byte data in the TEMP Register, and all 16-bits are written to the TCNT1 Timer/Counter1 Register simultaneously. Consequently, the High Byte TCNT1H must be accessed first for a full 16-bit register write operation. When the CPU reads the Low Byte TCNT1L, the data of the Low Byte TCNT1L is sent to the CPU and the data of the High Byte TCNT1H is placed in the TEMP Register. When the CPU reads the data in the High Byte TCNT1H, the CPU receives the data in the TEMP Register. Consequently, the Low Byte TCNT1L must be accessed first for a full 16-bit register read operation. The Timer/Counter1 is realized as an up or up/down (in PWM mode) counter with read and write access. If Timer/Counter1 is written to and a clock source is selected, the Timer/Counter1 continues counting in the timer clock cycle after it is preset with the written value. Timer/Counter1 Output Compare Register - OCR1AH and OCR1AL
TCNT1 Timer/Counter1 Read
Bit $2B ($4B) $2A ($4A)
15 MSB
14
13
12
11
10
9
8 OCR1AH LSB OCR1AL
7 Read/Write R/W R/W Initial Value 0 0
6 R/W R/W 0 0
5 R/W R/W 0 0
4 R/W R/W 0 0
3 R/W R/W 0 0
2 R/W R/W 0 0
1 R/W R/W 0 0
0 R/W R/W 0 0
Timer/Counter1 Output Compare Register - OCR1BH and OCR1BL
Bit $29 ($49) $28 ($48)
15 MSB
14
13
12
11
10
9
8 OCR1BH LSB OCR1BL
7 Read/Write R/W R/W Initial Value 0 0
6 R/W R/W 0 0
5 R/W R/W 0 0
4 R/W R/W 0 0
3 R/W R/W 0 0
2 R/W R/W 0 0
1 R/W R/W 0 0
0 R/W R/W 0 0
The Output Compare Registers are 16-bit read/write registers. The Timer/Counter1 Output Compare Registers contain the data to be continuously compared with Timer/Counter1. Actions on compare matches are specified in the Timer/Counter1 Control and Status Register. A software write to the Timer/Counter Register blocks compare matches in the next Timer/Counter clock cycle. This prevents immediate interrupts when initializing the Timer/Counter. A Compare Match will set the Compare Interrupt Flag in the CPU clock cycle following the compare event. Since the Output Compare Registers - OCR1A and OCR1B - are 16-bit registers, a temporary register TEMP is used when OCR1A/B are written to ensure that both bytes are updated simultaneously. When the CPU writes the High Byte, OCR1AH or OCR1BH, the data is temporarily stored in the TEMP Register. When the CPU writes the Low Byte, OCR1AL or OCR1BL, the TEMP Register is simultaneously written to OCR1AH or OCR1BH. Consequently, the High Byte OCR1AH or OCR1BH must be written first for a full 16-bit register write operation.
59
1457G-AVR-09/03
The TEMP Register is also used when accessing TCNT1 and ICR1. If the main program and also interrupt routines perform access to registers using TEMP, interrupts must be disabled during access from the main program and interrupt routines. Timer/Counter1 Input Capture Register - ICR1H and ICR1L
Bit $27 ($47) $26 ($46)
15 MSB
14
13
12
11
10
9
8 ICR1H LSB ICR1L
7 Read/Write R R Initial Value 0 0
6 R R 0 0
5 R R 0 0
4 R R 0 0
3 R R 0 0
2 R R 0 0
1 R R 0 0
0 R R 0 0
The Input Capture Register is a 16-bit read-only register. When the rising or falling edge (according to the Input Capture Edge setting - ICES1) of the signal at the Input Capture Pin - ICP - is detected, the current value of the Timer/Counter1 Register - TCNT1 - is transferred to the Input Capture Register - ICR1. At the same time, the Input Capture Flag - ICF1 - is set (one). Since the Input Capture Register - ICR1 - is a 16-bit register, a temporary register TEMP is used when ICR1 is read to ensure that both bytes are read simultaneously. When the CPU reads the Low Byte ICR1L, the data is sent to the CPU and the data of the High Byte ICR1H is placed in the TEMP Register. When the CPU reads the data in the High Byte ICR1H, the CPU receives the data in the TEMP Register. Consequently, the Low Byte ICR1L must be accessed first for a full 16-bit register read operation. The TEMP Register is also used when accessing TCNT1, OCR1A, and OCR1B. If the main program and also interrupt routines accesses registers using TEMP, interrupts must be disabled during access from the main program and interrupt routines. Timer/Counter1 In PWM Mode When the PWM mode is selected, Timer/Counter1 and the Output Compare Register1A - OCR1A and the Output Compare Register1B - OCR1B, form a dual 8-, 9-, or 10-bit, Free Running, Glitch-free, and phase correct PWM with outputs on the PD5(OC1A) and PD4(OC1B) pins. In this mode, the Timer/Counter1 acts as an up/down counter, counting up from $0000 to TOP (see Table 21), where it turns and counts down again to zero before the cycle is repeated. When the counter value matches the contents of the 8, 9, or 10 least significant bits (depending on resolution) of OCR1A or OCR1B, the PD5(OC1A)/PD4(OC1B) pins are set or cleared according to the settings of the COM1A1/COM1A0 or COM1B1/COM1B0 bits in the Timer/Counter1 Control Register TCCR1A. Refer to Table 17 on page 56 for details. Alternatively, the Timer/Counter1 can be configured to a PWM that operates at twice the speed as in the mode described above. Then the Timer/Counter1 and the Output Compare Register1A - OCR1A and the Output Compare Register1B - OCR1B, form a dual 8-, 9-, or 10-bit, free running and glitch-free PWM with outputs on the PD5(OC1A) and PD4(OC1B) pins..
60
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Table 20. Timer TOP Values and PWM Frequency
CTC1 0 0 0 1 1 1 PWM11 0 1 1 0 1 1 PWM10 1 0 1 1 0 1 PWM Resolution 8-bit 9-bit 10-bit 8-bit 9-bit 10-bit Timer TOP Value $00FF (255) $01FF (511) $03FF(1023) $00FF (255) $01FF (511) $03FF(1023) Frequency fTCK1/510 fTCK1/1022 fTCK1/2046 fTCK1/256 fTCK1/512 fTCK1/1024
As shown in Table 20, the PWM operates at either 8, 9, or 10 bits resolution. Note the unused bits in OCR1A, OCR1B, and TCNT1 will automatically be written to zero by hardware. I.e., bit 9 to 15 will be set to zero in OCR1A, OCR1B, and TCNT1 if the 9-bit PWM resolution is selected. This makes it possible for the user to perform Read-ModifyWrite operations in any of the three resolution modes and the unused bits will be treated as don't care. Table 21. Timer TOP Values and PWM Frequency
PWM Resolution 8-bit 9-bit 10-bit Timer TOP Value $00FF (255) $01FF (511) $03FF(1023) Frequency fTC1/510 fTC1/1022 fTC1/2046
Table 22. Compare1 Mode Select in PWM Mode(1)
CTC1 0 0 0 0 1 1 1 1 Note: COM1X1 0 0 1 1 0 0 1 1 1. X = A or B COM1X0 0 1 0 1 0 1 0 1 Effect on OCX1 Not connected Reserved Cleared on Compare Match, up-counting. Set on Compare Match, down-counting (non-inverted PWM). Cleared on Compare Match, down-counting. Set on Compare Match, up-counting (inverted PWM). Not connected Reserved Cleared on Compare Match, set on overflow. Set on Compare Match, cleared on overflow.
Note that in the PWM mode, the 8, 9, or 10 least significant OCR1A/OCR1B bits (depending on resolution), when written, are transferred to a temporary location. They are latched when Timer/Counter1 reaches the value TOP. This prevents the occurrence of odd-length PWM pulses (glitches) in the event of an unsynchronized OCR1A/OCR1B write. See Figure 38 and Figure 39 for an example in each mode.
61
1457G-AVR-09/03
Figure 38. Effects of Unsynchronized OCR1 Latching.
PWM Output OC1x Synchronized OC1x Latch
PWM Output OC1x Unsynchronized OC1x Latch
Note: x = A or B
Figure 39. Effects of Unsynchronized OCR1 Latching in Overflow Mode
PWM Output OC1x Synchronized OC1x Latch
PWM Output OC1x Unsynchronized OC1x Latch
Note: X = A or B
During the time between the write and the latch operation, a read from OCR1A or OCR1B will read the contents of the temporary location. This means that the most recently written value always will read out of OCR1A/B. When the OCR1X contains $0000 or TOP, and the up/down PWM mode is selected, the output OC1A/OC1B is updated to low or high on the next compare match according to the settings of COM1A1/COM1A0 or COM1B1/COM1B0. This is shown in Table 23. In overflow PWM mode, the output OC1A/OC1B is held low or high only when the Output Compare Register contains TOP.
62
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Table 23. PWM Outputs OCR1X = $0000 or TOP
COM1X1 1 1 1 1 COM1X0 0 0 1 1 OCR1X $0000 TOP $0000 TOP Output OC1X L H H L
In overflow PWM mode, the table above is only valid for OCR1X = TOP. In PWM mode, the Timer Overflow Flag1, TOV1, is set when the counter advances from $0000. In overflow PWM mode, the Timer Overflow Flag is set as in normal Timer/Counter mode. Timer Overflow Interrupt1 operates exactly as in normal Timer/Counter mode, i.e., it is executed when TOV1 is set provided that Timer Overflow Interrupt1 and global interrupts are enabled. This also applies to the Timer Output Compare1 Flags and interrupts.
63
1457G-AVR-09/03
Watchdog Timer
The Watchdog Timer is clocked from a separate On-chip Oscillator which runs at 1 Mhz. This is the typical value at VCC = 5V. See characterization data for typical values at other VCC levels. By controlling the Watchdog Timer prescaler, the Watchdog Reset interval can be adjusted as shown in Table 24 on page 65. The WDR - Watchdog Reset - instruction resets the Watchdog Timer. Eight different clock cycle periods can be selected to determine the reset period. If the reset period expires without another Watchdog Reset, the ATmega323 resets and executes from the Reset Vector. For timing details on the Watchdog Reset, refer to page 30. To prevent unintentional disabling of the Watchdog, a special turn-off sequence must be followed when the Watchdog is disabled. Refer to the description of the Watchdog Timer Control Register for details. Figure 40. Watchdog Timer
OSCILLATOR
1 MHz at VCC = 5V
The Watchdog Timer Control Register - WDTCR
Bit $21 ($41) Read/Write Initial Value
7 - R 0
6 - R 0
5 - R 0
4 WDTOE R/W 0
3 WDE R/W 0
2 WDP2 R/W 0
1 WDP1 R/W 0
0 WDP0 R/W 0 WDTCR
* Bits 7..5 - Res: Reserved Bits These bits are reserved bits in the ATmega323 and will always read as zero. * Bit 4 - WDTOE: Watchdog Turn-off Enable This bit must be set (one) when the WDE bit is cleared. Otherwise, the Watchdog will not be disabled. Once set, hardware will clear this bit to zero after four clock cycles. Refer to the description of the WDE bit for a Watchdog disable procedure. * Bit 3 - WDE: Watchdog Enable When the WDE is set (one) the Watchdog Timer is enabled, and if the WDE is cleared (zero) the Watchdog Timer function is disabled. WDE can only be cleared if the WDTOE bit is set(one). To disable an enabled Watchdog timer, the following procedure must be followed:
64
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
1. In the same operation, write a logical one to WDTOE and WDE. A logical one must be written to WDE even though it is set to one before the disable operation starts. 2. Within the next four clock cycles, write a logical 0 to WDE. This disables the Watchdog. * Bits 2..0 - WDP2, WDP1, WDP0: Watchdog Timer Prescaler 2, 1, and 0 The WDP2, WDP1, and WDP0 bits determine the Watchdog Timer prescaling when the Watchdog Timer is enabled. The different prescaling values and their corresponding Timeout Periods are shown in Table 24. Table 24. Watchdog Timer Prescale Select
WDP2 0 0 0 0 1 1 1 1 WDP1 0 0 1 1 0 0 1 1 WDP0 0 1 0 1 0 1 0 1 Number of WDT Oscillator Cycles 16K cycles 32K cycles 64K cycles 128K cycles 256K cycles 512K cycles 1,024K cycles 2,048K cycles Typical Time-out at VCC = 3.0V 47 ms 94 ms 0.19 s 0.38 s 0.75 s 1.5 s 3.0 s 6.0 s Typical Time-out at VCC = 5.0V 15 ms 30 ms 60 ms 0.12 s 0.24 s 0.49 s 0.97 s 1.9 s
65
1457G-AVR-09/03
EEPROM Read/Write Access
The EEPROM Access Registers are accessible in the I/O space. The write access time is in the range of 1.9 - 3.8 ms, depending on the frequency of the calibrated RC Oscillator. See Table 25 for details. A self-timing function, however, lets the user software detect when the next byte can be written. If the user code contains code that writes the EEPROM, some precautions must be taken. In heavily filtered power supplies, VCC is likely to rise or fall slowly on Power-up/down. This causes the device for some period of time to run at a voltage lower than specified as minimum for the clock frequency used. CPU operation under these conditions is likely to cause the Program Counter to perform unintentional jumps and possibly execute the EEPROM write code. To secure EEPROM integrity, the user is advised to use an external undervoltage reset circuit or the internal Brown-out Detector in this case. In order to prevent unintentional EEPROM writes, a specific write procedure must be followed. Refer to the description of the EEPROM Control Register for details on this. When the EEPROM is read, the CPU is halted for four clock cycles before the next instruction is executed. When the EEPROM is written, the CPU is halted for two clock cycles before the next instruction is executed.
The EEPROM Address Register - EEARH and EEARL
Bit $1F ($3F) $1E ($3E)
15 - EEAR7 7
14 - EEAR6 6 R R/W 0 X
13 - EEAR5 5 R R/W 0 X
12 - EEAR4 4 R R/W 0 X
11 - EEAR3 3 R R/W 0 X
10 - EEAR2 2 R R/W 0 X
9 EEAR9 EEAR1 1 R/W R/W X X
8 EEAR8 EEAR0 0 R/W R/W X X EEARH EEARL
Read/Write
R R/W
Initial Value
0 X
* Bits 15..10 - Res: Reserved Bits These bits are reserved bits in the ATmega323 and will always read as zero. * Bits 9..0 - EEAR9..0: EEPROM Address The EEPROM Address Registers - EEARH and EEARL specify the EEPROM address in the 1K bytes EEPROM space. The EEPROM data bytes are addressed linearly between 0 and 1,023. The initial value of EEAR is undefined. A proper value must be written before the EEPROM may be accessed. The EEPROM Data Register - EEDR
Bit $1D ($3D) Read/Write Initial Value
7 MSB R/W 0
6
5
4
3
2
1
0 LSB EEDR
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
* Bits 7..0 - EEDR7.0: EEPROM Data For the EEPROM write operation, the EEDR Register contains the data to be written to the EEPROM in the address given by the EEAR Register. For the EEPROM read operation, the EEDR contains the data read out from the EEPROM at the address given by EEAR.
66
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
The EEPROM Control Register - EECR
Bit $1C ($3C) Read/Write Initial Value
7 - R 0
6 - R 0
5 - R 0
4 - R 0
3 EERIE R/W 0
2 EEMWE R/W 0
1 EEWE R/W X
0 EERE R/W 0 EECR
* Bits 7..4 - Res: Reserved Bits These bits are reserved bits in the ATmega323 and will always read as zero. * Bit 3 - EERIE: EEPROM Ready Interrupt Enable When the I bit in SREG and EERIE are set (one), the EEPROM Ready Interrupt is enabled. When cleared (zero), the interrupt is disabled. The EEPROM Ready interrupt generates a constant interrupt when EEWE is cleared (zero). * Bit 2 - EEMWE: EEPROM Master Write Enable The EEMWE bit determines whether setting EEWE to one causes the EEPROM to be written. When EEMWE is set(one) setting EEWE will write data to the EEPROM at the selected address If EEMWE is zero, setting EEWE will have no effect. When EEMWE has been set (one) by software, hardware clears the bit to zero after four clock cycles. See the description of the EEWE bit for an EEPROM write procedure. * Bit 1 - EEWE: EEPROM Write Enable The EEPROM Write Enable Signal EEWE is the write strobe to the EEPROM. When address and data are correctly set up, the EEWE bit must be set to write the value into the EEPROM. The EEMWE bit must be set when the logical one is written to EEWE, otherwise no EEPROM write takes place. The following procedure should be followed when writing the EEPROM (the order of steps 2 and 3 is not essential): 1. Wait until EEWE becomes zero. 2. Write new EEPROM address to EEAR (optional). 3. Write new EEPROM data to EEDR (optional). 4. Write a logical one to the EEMWE bit while writing a zero to EEWE in EECR. 5. Within four clock cycles after setting EEMWE, write a logical one to EEWE. Caution: An interrupt between step 4 and step 5 will make the write cycle fail, since the EEPROM Master Write Enable will time-out. If an interrupt routine accessing the EEPROM is interrupting another EEPROM access, the EEAR or EEDR Register will be modified, causing the interrupted EEPROM access to fail. It is recommended to have the Global Interrupt Flag cleared during the 4 last steps to avoid these problems. When the write access time has elapsed, the EEWE bit is cleared (zero) by hardware. The user software can poll this bit and wait for a zero before writing the next byte. When EEWE has been set, the CPU is halted for two cycles before the next instruction is executed. * Bit 0 - EERE: EEPROM Read Enable The EEPROM Read Enable Signal EERE is the read strobe to the EEPROM. When the correct address is set up in the EEAR Register, the EERE bit must be set. When the EERE bit is cleared (zero) by hardware, requested data is found in the EEDR Register. The EEPROM read access takes one instruction, and there is no need to poll the EERE bit. When EERE has been set, the CPU is halted for four cycles before the next instruction is executed. 67
1457G-AVR-09/03
The user should poll the EEWE bit before starting the read operation. If a write operation is in progress, it is not possible to set the EERE bit, nor to change the EEAR Register. The calibrated Oscillator is used to time the EEPROM accesses. Table 25 lists the typical programming time for EEPROM access from the CPU. Table 25. EEPROM Programming Time.
Symbol EEPROM write (from CPU) Number of Calibrated RC Oscillator Cycles 2048 Min Programming Time 1.9 ms Max Programming Time 3.8 ms
Preventing EEPROM Corruption
During periods of low VCC, the EEPROM data can be corrupted because the supply voltage is too low for the CPU and the EEPROM to operate properly. These issues are the same as for board level systems using the EEPROM, and the same design solutions should be applied. An EEPROM data corruption can be caused by two situations when the voltage is too low. First, a regular write sequence to the EEPROM requires a minimum voltage to operate correctly. Secondly, the CPU itself can execute instructions incorrectly, if the supply voltage for executing instructions is too low. EEPROM data corruption can easily be avoided by following these design recommendations (one is sufficient): 1. Keep the AVR RESET active (low) during periods of insufficient power supply voltage. This can be done by enabling the internal Brown-out Detector (BOD) if the operating voltage matches the detection level. If not, an external low VCC Reset Protection circuit can be used. If a Reset occurs while a write operation is in progress, the write operation will be completed provided that the power supply is voltage is sufficient. 2. Keep the AVR core in Power-down sleep mode during periods of low VCC. This will prevent the CPU from attempting to decode and execute instructions, effectively protecting the EEPROM Registers from unintentional writes. 3. Store constants in Flash memory if the ability to change memory contents from software is not required. Flash memory can not be updated by the CPU unless the Boot Loader software supports writing to the Flash and the Boot Lock bits are configured so that writing to the Flash memory from CPU is allowed. See "Boot Loader Support" on page 177 for details.
68
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Serial Peripheral Interface - SPI
The Serial Peripheral Interface (SPI) allows high-speed synchronous data transfer between the ATmega323 and peripheral devices or between several AVR devices. The ATmega323 SPI includes the following features: * Full-duplex, Three-wire Synchronous Data Transfer * Master or Slave Operation * LSB First or MSB First Data Transfer * Seven Programmable Bit Rates * End of Transmission Interrupt Flag * Write Collision Flag Protection * Wake-up from Idle Mode * Double Speed (CK/2) Master SPI Mode Figure 41. SPI Block Diagram
DIVIDER /2/4/8/16/32/64/128
SPI2X
The interconnection between Master and Slave CPUs with SPI is shown in Figure 42. The PB7(SCK) pin is the clock output in the Master mode and the clock input in the Slave mode. Writing to the SPI Data Register of the Master CPU starts the SPI clock generator, and the data written shifts out of the PB5(MOSI) pin and into the PB5(MOSI) pin of the Slave CPU. After shifting one byte, the SPI clock generator stops, setting the end of Transmission Flag (SPIF). If the SPI Interrupt Enable bit (SPIE) in the SPCR Register is set, an interrupt is requested. The Slave Select input, PB4(SS), is set low to select an individual Slave SPI device. The two Shift Registers in the Master and the Slave can be considered as one distributed 16-bit circular Shift Register. This is shown in Figure 42. When data is shifted from the Master to the Slave, data is also shifted in the opposite direction, simultaneously. During one shift cycle, data in the Master and the Slave is interchanged.
SPI2X
69
1457G-AVR-09/03
Figure 42. SPI Master-Slave Interconnection
MSB MASTER LSB MISO MOSI MISO MOSI MSB SLAVE LSB 8 BIT SHIFT REGISTER 8 BIT SHIFT REGISTER
SPI CLOCK GENERATOR
SCK SS VCC
SCK SS
The system is single buffered in the transmit direction and double buffered in the receive direction. This means that bytes to be transmitted cannot be written to the SPI Data Register before the entire shift cycle is completed. When receiving data, however, a received character must be read from the SPI Data Register before the next character has been completely shifted in. Otherwise, the first byte is lost. When the SPI is enabled, the data direction of the MOSI, MISO, SCK, and SS pins is overridden according to Table 26. Table 26. SPI Pin Overrides(1)
Pin MOSI MISO SCK SS Note: Direction, Master SPI User Defined Input User Defined User Defined Direction, Slave SPI Input User Defined Input Input
1. See "Alternate Functions of Port B" on page 140 for a detailed description of how to define the direction of the user defined SPI pins.
SS Pin Functionality
When the SPI is configured as a Master (MSTR in SPCR is set), the user can determine the direction of the SS pin. If SS is configured as an output, the pin is a general output pin which does not affect the SPI system. If SS is configured as an input, it must be held high to ensure Master SPI operation. If the SS pin is driven low by peripheral circuitry when the SPI is configured as a Master with the SS pin defined as an input, the SPI system interprets this as another Master selecting the SPI as a Slave and starting to send data to it. To avoid bus contention, the SPI system takes the following actions: 1. The MSTR bit in SPCR is cleared and the SPI system becomes a Slave. As a result of the SPI becoming a Slave, the MOSI and SCK pins become inputs. 2. The SPIF Flag in SPSR is set, and if the SPI interrupt is enabled, and the I-bit in SREG is set, the interrupt routine will be executed. Thus, when interrupt-driven SPI transmission is used in Master mode, and there exists a possibility that SS is driven low, the interrupt should always check that the MSTR bit is still set. If the MSTR bit has been cleared by a Slave Select, it must be set by the user to re-enable SPI Master mode. When the SPI is configured as a Slave, the SS pin is always input. When SS is held low, the SPI is activated, and MISO becomes an output if configured so by the user. All other pins are inputs. When SS is driven high, all pins are inputs, and the SPI is passive, which means that it will not receive incoming data. Note that the SPI logic will be reset
70
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
once the SS pin is driven high. If the SS pin is driven high during a transmission, the SPI will stop sending and receiving immediately and both data received and data sent must be considered as lost.
Data Modes
There are four combinations of SCK phase and polarity with respect to serial data, which are determined by control bits CPHA and CPOL. The SPI data transfer formats are shown in Figure 43 and Figure 44. Figure 43. SPI Transfer Format with CPHA = 0 and DORD = 0(1)
Note:
1. * Not defined but normally MSB of character just received.
Figure 44. SPI Transfer Format with CPHA = 1 and DORD = 0(1)
Note:
1. * Not defined but normally LSB of previously transmitted character.
SPI Control Register - SPCR
Bit $0D ($2D) Read/Write Initial Value 7 SPIE R/W 0 6 SPE R/W 0 5 DORD R/W 0 4 MSTR R/W 0 3 CPOL R/W 0 2 CPHA R/W 0 1 SPR1 R/W 0 0 SPR0 R/W 0 SPCR
* Bit 7 - SPIE: SPI Interrupt Enable This bit causes the SPI interrupt to be executed if SPIF bit in the SPSR Register is set and the if the Global Interrupt Enable bit in SREG is set. * Bit 6 - SPE: SPI Enable When the SPE bit is set (one), the SPI is enabled. This bit must be set to enable any SPI operations.
71
1457G-AVR-09/03
* Bit 5 - DORD: Data Order When the DORD bit is set (one), the LSB of the data word is transmitted first. When the DORD bit is cleared (zero), the MSB of the data word is transmitted first. * Bit 4 - MSTR: Master/Slave Select This bit selects Master SPI mode when set (one), and Slave SPI mode when cleared (zero). If SS is configured as an input and is driven low while MSTR is set, MSTR will be cleared, and SPIF in SPSR will become set. The user will then have to set MSTR to reenable SPI Master mode. * Bit 3 - CPOL: Clock Polarity When this bit is set (one), SCK is high when idle. When CPOL is cleared (zero), SCK is low when idle. Refer to Figure 43 and Figure 44 for additional information. * Bit 2 - CPHA: Clock Phase Refer to Figure 43 and Figure 44 for the functionality of this bit. * Bits 1, 0 - SPR1, SPR0: SPI Clock Rate Select 1 and 0 These two bits control the SCK rate of the device configured as a Master. SPR1 and SPR0 have no effect on the Slave. The relationship between SCK and the Oscillator Clock frequency fck is shown in Table 27. Table 27. Relationship Between SCK and the Oscillator Frequency
SPI2X 0 0 0 0 1 1 1 1 SPR1 0 0 1 1 0 0 1 1 SPR0 0 1 0 1 0 1 0 1 SCK Frequency fck/4 fck/16 fck/64 fck/128 fck/2 fck/8 fck/32 fck /64
The SPI Status Register - SPSR
Bit $0E ($2E) Read/Write Initial Value
7 SPIF R 0
6 WCOL R 0
5 - R 0
4 - R 0
3 - R 0
2 - R 0
1 - R 0
0 SPI2X R/W 0 SPSR
* Bit 7 - SPIF: SPI Interrupt Flag When a serial transfer is complete, the SPIF bit is set (one) and an interrupt is generated if SPIE in SPCR is set (one) and global interrupts are enabled. If SS is an input and is driven low when the SPI is in Master mode, this will also set the SPIF Flag. SPIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, the SPIF bit is cleared by first reading the SPI Status Register with SPIF set (one), then accessing the SPI Data Register (SPDR).
72
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
* Bit 6 - WCOL: Write COLlision Flag The WCOL bit is set if the SPI Data Register (SPDR) is written during a data transfer. The WCOL bit (and the SPIF bit) are cleared (zero) by first reading the SPI Status Register with WCOL set (one), and then accessing the SPI Data Register. * Bit 5..1 - Res: Reserved Bits These bits are reserved bits in the ATmega323 and will always read as zero. * Bit 0 - SPI2X: Double SPI Speed Bit When this bit is set (one) the SPI speed (SCK Frequency) will be doubled when the SPI is in Master mode (see Table 27). This means that the minimum SCK period will be 2 CPU clock periods. When the SPI is configured as Slave, the SPI is only guaranteed to work at fck/4 or lower. The SPI interface on the ATmega323 is also used for Program memory and EEPROM downloading or uploading. See page 197 for Serial Programming and verification. The SPI Data Register - SPDR
Bit $0F ($2F) Read/Write Initial Value 7 MSB R/W X R/W X R/W X R/W X R/W X R/W X R/W X 6 5 4 3 2 1 0 LSB R/W X Undefined SPDR
The SPI Data Register is a read/write register used for data transfer between the Register File and the SPI Shift Register. Writing to the register initiates data transmission. Reading the register causes the Shift Register Receive buffer to be read.
73
1457G-AVR-09/03
USART
The Universal Synchronous and Asynchronous serial Receiver and Transmitter (USART) is a highly flexible serial communication device. The main features are: * Full Duplex Operation (Independent Serial Receive and Transmit Registers) * Asynchronous or Synchronous Operation * Master or Slave Clocked Synchronous Operation * High Resolution Baud Rate Generator * Supports Serial Frames with 5, 6, 7, 8, or 9 Data Bits and 1 or 2 Stop Bits * Odd or Even Parity Generation and Parity Check Supported by Hardware * Data OverRun Detection * Framing Error Detection * Noise Filtering Includes False Start Bit Detection and Digital Low Pass Filter * Three Separate Interrupts on TX Complete, TX Data Register Empty and RX Complete * Multi-processor Communication Mode * Double Speed Asynchronous Communication Mode A simplified block diagram of the USART Transmitter is shown in Figure 45. CPU accessible I/O Registers and I/O pins are shown in bold. Figure 45. USART Block Diagram
Overview
Clock Generator
UBRR[H:L] OSC
BAUD RATE GENERATOR
SYNC LOGIC
PIN CONTROL
XCK
Transmitter
UDR (Transmit) PARITY GENERATOR TRANSMIT SHIFT REGISTER PIN CONTROL TxD TX CONTROL
DATABUS
Receiver
CLOCK RECOVERY RX CONTROL
RECEIVE SHIFT REGISTER
DATA RECOVERY
PIN CONTROL
RxD
UDR (Receive)
PARITY CHECKER
UCSRA
UCSRB
UCSRC
The dashed boxes in the block diagram separates the three main parts of the USART (listed from the top): Clock Generation, Transmitter and Receiver. Control Registers are shared by all units. The clock generation logic consists of synchronization logic for external clock input used by Synchronous Slave operation, and the baud rate generator. The
74
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
XCK (transfer clock) pin is only used by synchronous transfer mode. The Transmitter consists of a single write buffer, a serial Shift Register, Parity Generator and control logic for handling different serial frame formats. The write buffer allows a continuous transfer of data without any delay between frames. The Receiver is the most complex part of the USART module due to its clock and data recovery units. The recovery units are used for asynchronous data reception. In addition to the recovery units, the Receiver includes a parity checker, control logic, a Shift Register and a two level receive buffer (UDR). The Receiver supports the same frame formats as the Transmitter, and can detect Frame Error, Data OverRun and Parity Errors.
ATmega323 USART Pin Specification
Table 28 shows the ATmega323 specific USART pin placement. Table 28. ATmega323 Specific USART Pin Placement
USART Pin Name RxD TxD XCK Corresponding ATmega323 Pin PD0 PD1 PB0
As XCK is placed on PB0, DDR_XCK in the following refers to DDB0.
About Code Examples
This USART documentation contains simple code examples that briefly show how to use the USART. These code examples assume that the part specific header file is included before compilation. Be aware that not all C compiler vendors include bit definitions in the header files, and that interrupt handling in C is compiler dependent. Please confirm with the C compiler documentation. The USART is fully compatible with the AVR UART regarding: * * * * * Bit locations inside all USART Registers Baud Rate Generation Transmitter Operation Transmit Buffer Functionality Receiver Operation
AVR USART vs. AVR UART - Compatibility
However, the receive buffering has two improvements that will affect the compatibility in some special cases: * A second Buffer Register has been added. The two Buffer Registers operates as a circular FIFO buffer. Therefore the UDR must only be read once for each incoming data. More important is the fact that the Error Flags (FE and DOR) and the ninth data bit (RXB8) are buffered with the data in the receive buffer. Therefore the status bits must always be read before the UDR Register is read. Otherwise the error status will be lost since the buffer state is lost. The Receiver Shift Register can now act as a third buffer level. This is done by allowing the received data to remain in the Serial Shift Register (see Figure 45) if the Buffer Registers are full, until a new start bit is detected. The USART is therefore more resistant to Data OverRun (DOR) error conditions.
*
The following control bits have changed name, but have same functionality and register location: * * CHR9 is changed to UCSZ2 OR is changed to DOR
75
1457G-AVR-09/03
Clock Generation
The Clock Generation Logic generates the base clock for the Transmitter and Receiver. The USART supports four modes of clock operation: Normal asynchronous, Double Speed asynchronous, Master synchronous and Slave synchronous mode. The UMSEL bit in USART Control and Status Register C (UCSRC) selects between asynchronous and synchronous operation. Double Speed (asynchronous mode only) is controlled by the U2X found in the UCSRA Register. When using synchronous mode (UMSEL = 1), the Data Direction Register for the XCK pin (DDR_XCK) controls whether the clock source is internal (Master mode) or external (Slave mode). The XCK pin is only active when using synchronous mode. Figure 46 shows a block diagram of the clock generation logic. Figure 46. Clock Generation Logic, Block Diagram
UBRR fosc Prescaling Down-Counter UBRR+1 /2 /4 /2 U2X
0 1 0 DDR_XCK 1
OSC
txclk
xcki XCK Pin xcko
Sync Register
Edge Detector
0 1
UMSEL
DDR_XCK
UCPOL
1 0
rxclk
Signal description: txclk rxclk xcki xcko fosc Internal Clock Generation - The Baud Rate Generator Transmitter clock. (Internal Signal) Receiver base clock. (Internal Signal) Input from XCK pin (internal Signal). Used for Synchronous Slave operation. Clock output to XCK pin (Internal Signal). Used for synchronous Master operation. XTAL pin frequency (System Clock).
Internal clock generation is used for the asynchronous and the synchronous Master modes of operation. The description in this section refers to Figure 46. The USART Baud Rate Register (UBRR) and the down-counter connected to it function as a programmable prescaler or baud rate generator. The down-counter, running at system clock (fosc), is loaded with the UBRR value each time the counter has counted down to zero or when the UBRRL Register is written. A clock is generated each time the count er re aches zero. Thi s clock is t he b aud rate generat or clock o utput (= fosc/(UBRR+1)). The Transmitter divides the baud rate generator clock output by 2, 8, or 16 depending on mode. The baud rate generator output is used directly by the Receiver's clock and data recovery units. However, the recovery units use a state machine that uses 2, 8, or 16 states depending on mode set by the state of the UMSEL, U2X and DDR_XCK bits.
76
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Table 29 contains equations for calculating the baud rate (in bits per second) and for calculating the UBRR value for each mode of operation using an internally generated clock source. Table 29. Equations for Calculating Baud Rate Register Setting
Operating Mode Asynchronous Normal Mode (U2X = 0) Asynchronous Double Speed Mode (U2X = 1) Synchronous Master Mode Note: Equation for Calculating Baud Rate(1) Equation for Calculating UBRR Value
f OSC BAUD = --------------------------------------16 ( UBRR + 1 ) f OSC BAUD = ----------------------------------8 ( UBRR + 1 ) f OSC BAUD = ----------------------------------2 ( UBRR + 1 )
f OSC UBRR = ----------------------- - 1 16BAUD f OSC UBRR = -------------------- - 1 8BAUD f OSC UBRR = -------------------- - 1 2BAUD
1. The baud rate is defined to be the transfer rate in bit per second (bps). BAUD Baud rate (in bits per second, bps) System Oscillator clock frequency fOSC UBRR Contents of the UBRRH and UBRRL Registers, (0 - 4095) Some examples of UBRR values for some system clock frequency are found in Table 36 (see page 99).
Double Speed Operation (U2X)
The transfer rate can be doubled by setting the U2X bit in UCSRA. Setting this bit only has effect for the asynchronous operation. Set this bit to zero when using synchronous operation. Setting this bit will reduce the divisor of the baud rate divider from 16 to 8, effectively doubling the transfer rate for asynchronous communication. Note however that the Receiver will in this case only use half the number of samples (reduced from 16 to 8) for data sampling and clock recovery, and therefore a more accurate baud rate setting and system clock are required when this mode is used. For the Transmitter, there are no downsides.
External Clock
External clocking is used by the Synchronous Slave modes of operation. The description in this section refers to Figure 46 for details. External clock input from the XCK pin is sampled by a synchronization register to minimize the chance of meta-stability. The output from the synchronization register must then pass through an edge detector before it can be used by the Transmitter and Receiver. This process introduces a two CPU clock period delay and therefore the maximum external XCK clock frequency is limited by the following equation: f OSC f XCK < ---------4 Note that fosc depends on the stability of the system clock source. It is therefore recommended to add some margin to avoid possible loss of data due to frequency variations.
Synchronous Clock Operation When synchronous mode is used (UMSEL = 1), the XCK pin will be used as either clock input (Slave) or clock output (Master). The dependency between the clock edges and data sampling or data change is the same. The basic principle is that data input (on RxD) is sampled at the opposite XCK clock edge of the edge the data output (TxD) is changed.
77
1457G-AVR-09/03
Figure 47. Synchronous Mode XCK Timing
UCPOL = 0 XCK RxD / TxD Sample UCPOL = 1 XCK RxD / TxD Sample
The UCPOL bit UCRSC selects which XCK clock edge is used for data sampling and which is used for data change. As Figure 47 shows, when UCPOL is zero the data will be changed at falling XCK edge and sampled at rising XCK edge. If UCPOL is set, the data will be changed at rising XCK edge and sampled at falling XCK edge.
Frame Formats
A serial frame is defined to be one character of data bits with synchronization bits (start and stop bits), and optionally a parity bit for error checking. The USART accept all 30 combinations of the following as valid frame formats: * * * * 1 start bit 5, 6, 7, 8, or 9 data bits no, even, or odd parity bit 1 or 2 stop bits
A frame starts with the start bit followed by the least significant data bit. Then the next data bits, up to a total of nine, are succeeding, ending with the most significant bit. If enabled, the parity bit is inserted after the data bits, before the stop bits. When a complete frame is transmitted, it can be directly followed by a new frame, or the communication line can be set to a idle (high) state. Figure 48 illustrates the possible combinations of the frame formats. Bits inside brackets are optional. Figure 48. Frame Formats
FRAME
(IDLE)
St
0
1
2
3
4
[5]
[6]
[7]
[8]
[P]
Sp1 [Sp2]
(St / IDLE)
St (n) P Sp IDLE
Start bit, always low. Data bits (0 to 8). Parity bit. Can be odd or even. Stop bit, always high. No transfers on the communication line (RxD or TxD). An IDLE line must be high.
78
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
The frame format used by the USART is set by the UCSZ2:0, UPM1:0 and USBS bits in UCSRB and UCSRC. The Receiver and Transmitter uses the same setting. Note that changing the setting of any of these bits will corrupt all ongoing communication for both the Receiver and Transmitter. The USART Character SiZe (UCSZ2:0) bits select the number of data bits in the frame. The USART Parity Mode (UPM1:0) bits enable and set the type of parity bit. The selection between one or two stop bits is done by the USART Stop Bit Select (USBS) bit. The Receiver ignores the second stop bit. An FE (Frame Error) will therefore only be detected in the cases where the first stop bit is zero.
Parity Bit Calculation
The parity bit is calculated by doing an exclusive-or of all the data bits. If odd parity is used, the result of the exclusive or is inverted. The relation between the parity bit and data bits is as follows: P ev en = d n - 1 ... d 3 d 2 d 1 d 0 0 P odd = d n - 1 ... d 3 d 2 d 1 d 0 1 Peven Podd dn Parity bit using even parity Parity bit using odd parity Data bit n of the character
If used, the parity bit is located between the last data bit and first stop bit of a serial frame.
USART Initialization
The USART has to be initialized before any communication can take place. The initialization process normally consists of setting the baud rate, setting frame format and enabling the Transmitter or the Receiver depending on the usage. For interrupt driven USART operation, the Global Interrupt Flag should be cleared (and interrupts globally disabled) when doing the initialization. Before doing a re-initialization with changed baud rate or frame format, be sure that there are no ongoing transmissions during the period the registers are changed. The TXC Flag can be used to check that the Transmitter has completed all transfers, and the RXC Flag can be used to check that there are no unread data in the Receive Buffer. Note that the TXC Flag must be cleared before each transmission (before UDR is written) if it is used for this purpose. The following simple USART initialization code examples show one assembly and one C function that is equal in functionality. The examples assume asynchronous operation using polling (no interrupts enabled) and a fixed frame format. The baud rate is given as a function parameter. For the assembly code, the baud rate parameter is assumed to be stored in the r17:r16 Registers. When the function writes to the UCSRC Register, the URSEL bit (MSB) must be set due to the sharing of I/O location by UBRRH and UCSRC.
79
1457G-AVR-09/03
Assembly Code Example(1)
USART_Init: ; Set baud rate out UBRRH, r17 out UBRRL, r16 ; Enable Receiver and Transmitter ldi r16, (1<C Code Example(1)
void USART_Init( unsigned int baud ) { /* Set baud rate */ UBRRH = (unsigned char)(baud>>8); UBRRL = (unsigned char)baud; /* Enable Receiver and Transmitter */ UCSRB = (1<Note:
1. The example code assumes that the part specific header file is included.
More advanced initialization routines can be made that include frame format as parameters, disable interrupts and so on. However, many applications use a fixed setting of the Baud and Control Registers, and for these types of applications the initialization code can be placed directly in the main routine, or be combined with initialization code for other I/O modules.
80
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Data Transmission - The USART Transmitter
The USART Transmitter is enabled by setting the Transmit Enable (TXEN) bit in the UCSRB Register. When the Transmitter is enabled, the normal port operation of the TxD pin is overridden by the USART and given the function as the Transmitter's serial output. The baud rate, mode of operation and frame format must be set up once before doing any transmissions. If synchronous operation is used, the clock on the XCK pin will be overridden and used as transmission clock. A data transmission is initiated by loading the transmit buffer with the data to be transmitted. The CPU can load the transmit buffer by writing to the UDR I/O location. The buffered data in the Transmit Buffer will be moved to the Shift Register when the Shift Register is ready to send a new frame. The Shift Register is loaded with new data if it is in idle state (no ongoing transmission) or immediately after the last stop bit of the previous frame is transmitted. When the Shift Register is loaded with new data, it will transfer one complete frame at the rate given by the Baud Register, U2X bit or by XCK depending on mode of operation. The following code examples show a simple USART Transmit function based on polling of the Data Register Empty (UDRE) Flag. When using frames with less than eight bit, the most significant bits written to the UDR are ignored. The USART has to be initialized before the function can be used. For the assembly code, the data to be sent is assumed to be stored in Register R16. Assembly Code Example(1)
USART_Transmit: ; Wait for empty transmit buffer sbis UCSRA,UDRE rjmp USART_Transmit ; Put data (r16) into buffer, sends the data out ret UDR,r16
Sending Frames with 5 to 8 Data Bit
C Code Example
void USART_Transmit( unsigned char data ) { /* Wait for empty transmit buffer */ while ( !( UCSRA & (1<Note:
1. The example code assumes that the part specific header file is included.
The function simply waits for the Transmit Buffer to be empty by checking the UDRE Flag, before loading it with new data to be transmitted. If the Data Register Empty Interrupt is utilized, the interrupt routine writes the data into the buffer.
81
1457G-AVR-09/03
Sending Frames with 9 Data Bit
If 9-bit characters are used (UCSZ = 7), the ninth bit must be written to the TXB8 bit in UCSRB before the Low Byte of the character written to UDR. The following code examples show a transmit function that handles 9-bit characters. For the assembly code, the data to be sent is assumed to be stored in Registers R17:R16. Assembly Code Example(1)
USART_Transmit: ; Wait for empty transmit buffer sbis UCSRA,UDRE rjmp USART_Transmit ; Copy ninth bit from r17 to TXB8 cbi sbi UCSRB,TXB8 UCSRB,TXB8
sbrc r17,0 ; Put LSB data (r16) into buffer, sends the data out ret UDR,r16
C Code Example
void USART_Transmit( unsigned int data ) { /* Wait for empty transmit buffer */ while ( !( UCSRA & (1<Note:
1. These transmit functions are written to be general functions. They can be optimized if the contents of the UCSRB is static. I.e., only the TXB8 bit of the UCSRB Register is used after initialization.
The ninth bit can be used for indicating an address frame when using multi processor communication mode or for other protocol handling as for example synchronization. Transmitter Flags and Interrupts The USART Transmitter has two flags that indicate its state: USART Data Register Empty (UDRE) and Transmit Complete (TXC). Both flags can be used for generating interrupts. The Data Register Empty (UDRE) Flag indicates whether the transmit buffer is ready to receive new data. This bit is set when the transmit buffer is empty, and cleared when the transmit buffer contains data to be transmitted that has not yet been moved into the Shift Register. For compatibility with future devices, always set this bit to zero when writing the UCSRA Register. When the Data Register Empty Interrupt Enable (UDRIE) bit in UCSRB is set, the USART Data Register Empty Interrupt will be executed as long as UDRE is set (provided that global interrupts are enabled). UDRE is cleared by writing UDR. When interrupt-driven data transmission is used, the Data Register empty Interrupt routine must either write new data to UDR in order to clear UDRE or disable the Data Register
82
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Empty Interrupt, otherwise a new interrupt will occur once the interrupt routine terminates. The Transmit Complete (TXC) Flag bit is set one when the entire frame in the Transmit Shift Register has been shifted out and there are no new data currently present in the Transmit Buffer. The TXC Flag bit is automatically cleared when a Transmit Complete Interrupt is executed, or it can be cleared by writing a one to its bit location. The TXC Flag is useful in half-duplex communication interfaces (like the RS-485 standard), where a transmitting application must enter Receive mode and free the communication bus immediately after completing the transmission. When the Transmit Compete Interrupt Enable (TXCIE) bit in UCSRB is set, the USART Transmit Complete Interrupt will be executed when the TXC Flag becomes set (provided that global interrupts are enabled). When the Transmit Complete Interrupt is used, the interrupt handling routine does not have to clear the TXC Flag, this is done automatically when the interrupt is executed. Parity Generator The Parity Generator calculates the parity bit for the serial frame data. When parity bit is enabled (UPM1 = 1), the Transmitter control logic inserts the parity bit between the last data bit and the first stop bit of the frame that is sent. The disabling of the Transmitter (setting the TXEN to zero) will not become effective until ongoing and pending transmissions are completed, i.e., when the Transmit Shift Register and Transmit Buffer Register does not contain data to be transmitted. When disabled, the Transmitter will no longer override the TxD pin.
Disabling the Transmitter
83
1457G-AVR-09/03
Data Reception - The USART Receiver
The USART Receiver is enabled by setting the Receive Enable (RXEN) bit in the UCSRB Register. When the Receiver is enabled, the normal pin operation of the RxD pin is overridden by the USART and given the function as the Receiver's serial input. The baud rate, mode of operation and frame format must be set up once before any serial reception can be done. If synchronous operation is used, the clock on the XCK pin will be used as transfer clock. The Receiver starts data reception when it detects a valid start bit. Each bit that follows the start bit will be sampled at the baud rate or XCK clock, and shifted into the Receive Shift Register until the first stop bit of a frame is received. A second stop bit will be ignored by the Receiver. When the first stop bit is received, i.e., a complete serial frame is present in the Receive Shift Register, the contents of the Shift Register will be moved into the receive buffer. The receive buffer can then be read by reading the UDR I/O location. The following code example shows a simple USART Receive function based on polling of the Receive Complete (RXC) Flag. When using frames with less than eight bits the most significant bits of the data read from the UDR will be masked to zero. The USART has to be initialized before the function can be used. Assembly Code Example(1)
USART_Receive: ; Wait for data to be received sbis UCSRA, RXC rjmp USART_Receive ; Get and return received data from buffer in ret r16, UDR
Receiving Frames with 5 to 8 Data Bits
C Code Example
unsigned char USART_Receive( void ) { /* Wait for data to be received */ while ( !(UCSRA & (1<Note:
1. The example code assumes that the part specific header file is included.
The function simply waits for data to be present in the receive buffer by checking the RXC Flag, before reading the buffer and returning the value.
84
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Receiving Frames with 9 Data Bits If 9-bit characters are used (UCSZ=7) the ninth bit must be read from the RXB8 bit in UCSRB before reading the low bits from the UDR. This rule applies to the FE, DOR, and PE Status Flags as well. Read status from UCSRA, then data from UDR. Reading the UDR I/O location will change the state of the receive buffer FIFO and consequently the TXB8, FE, DOR and PE bits, which all are stored in the FIFO, will change. The following code example shows a simple USART receive function that handles both nine bit characters and the status bits. Assembly Code Example(1)
USART_Receive: ; Wait for data to be received sbis UCSRA, RXC rjmp USART_Receive ; Get status and ninth bit, then data from buffer in in in r18, UCSRA r17, UCSRB r16, UDR
; If error, return -1 andi r18,(1<USART_ReceiveNoError: ; Filter the ninth bit, then return lsr r17 andi r17, 0x01 ret
C Code Example(1)
unsigned int USART_Receive( void ) { unsigned char status, resh, resl; /* Wait for data to be received */ while ( !(UCSRA & (1<> 1) & 0x01; return ((resh << 8) | resl); }
Note:
1. The example code assumes that the part specific header file is included.
85
1457G-AVR-09/03
The receive function example reads all the I/O Registers into the Register File before any computation is done. This gives an optimal receive buffer utilization since the buffer location read will be free to accept new data as early as possible. Receive Compete Flag and Interrupt The USART Receiver has one flag that indicates the Receiver state. The Receive Complete (RXC) Flag indicates if there are unread data present in the receive buffer. This flag is one when unread data exist in the receive buffer, and zero when the receive buffer is empty (i.e. does not contain any unread data). If the Receiver is disabled (RXEN = 0), the receive buffer will be flushed and consequently the RXC bit will become zero. When the Receive Complete Interrupt Enable (RXCIE) in UCSRB is set, the USART Receive Complete Interrupt will be executed as long as the RXC Flag is set (provided that global interrupts are enabled). When interrupt-driven data reception is used, the receive complete routine must read the received data from UDR in order to clear the RXC Flag, otherwise a new interrupt will occur once the interrupt routine terminates. Receiver Error Flags The USART Receiver has three Error Flags: Frame Error (FE), Data OverRun (DOR) and Parity Enable (PE). All can be accessed by reading UCSRA. Common for the Error Flags is that they are located in the receive buffer together with the frame for which they indicate the error status. Due to the buffering of the Error Flags, the UCSRA must be read before the receive buffer (UDR), since reading the UDR I/O location changes the buffer read location. Another equality for the Error Flags is that they can not be altered by software doing a write to the flag location. However, all flags must be set to zero when the UCSRA is written for upward compatibility of future USART implementations. None of the Error Flags can generate interrupts. The Frame Error (FE) Flag indicates the state of the first stop bit of the next readable frame stored in the receive buffer. The FE Flag is zero when the stop bit was correctly read (as one), and the FE Flag will be one when the stop bit was incorrect (zero). This flag can be used for detecting out-of-sync conditions, detecting break conditions and protocol handling. The FE Flag is not affected by the setting of the USBS bit in UCSRC since the Receiver ignores all, except for the first, stop bits. For compatibility with future devices, always set this bit to zero when writing to UCSRA. The Data OverRun (DOR) Flag indicates data loss due to a Receiver buffer full condition. A Data OverRun occurs when the receive buffer is full (two characters), it is a new character waiting in the Receive Shift Register, and a new start bit is detected. If the DOR Flag is set there was one or more serial frame lost between the frame last read from UDR, and the next frame read from UDR. For compatibility with future devices, always set this bit to zero when writing to UCSRA. The DOR Flag is cleared when the frame received was successfully moved from the Shift Register to the receive buffer. The Parity Error (PE) Flag indicates that the next frame in the receive buffer did have an parity error when received. If parity check is not enabled the PE bit will always be read zero. For compatibility with future devices, always set this bit to zero when writing to UCSRA. For more details see "Parity Bit Calculation" on page 79 and "Parity Checker" on page 87.
86
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Parity Checker The parity checker is active when the high USART Parity Mode (UPM1) bit is set. Type of parity check to be performed (odd or even) is selected by the UPM0 bit. When enabled, the parity checker calculates the parity of the data bits in incoming frames and compares the result with the parity bit from the serial frame. The result of the check is stored in the receive buffer together with the received data and stop bits. The Parity Error (PE) Flag can then be read by software to check if the frame had a parity error. The PE bit is set if the next character that can be read from the receive buffer had a parity error when received and the parity checking was enabled at that point (UPM1 = 1). This bit is valid until the receive buffer (UDR) is read. Disabling the Receiver In contrast to the Transmitter, disabling the of the Receiver will be immediate. Data from ongoing receptions will therefore be lost. When disabled (i.e. the RXEN is set to zero) the Receiver will no longer override the normal function of the RxD port pin. The Receiver Buffer FIFO will be flushed when the Receiver is disabled. Remaining data in the buffer will be lost The Receiver Buffer FIFO will be flushed when the Receiver is disabled, i.e., the buffer will be emptied of its contents. Unread data will be lost. If the buffer has to be flushed during normal operation, due to for instance an error condition, read the UDR I/O location until the RXC Flag is cleared. The following code example shows how to flush the receive buffer. Assembly Code Example(1)
USART_Flush: sbis UCSRA, RXC ret in r16, UDR rjmp USART_Flush
Flushing the Receive Buffer
C Code Example(1)
void USART_Flush( void ) { unsigned char dummy; while ( UCSRA & (1<Note:
1. The example code assumes that the part specific header file is included.
87
1457G-AVR-09/03
Asynchronous Data Reception
The USART includes a clock recovery and a data recovery unit for handling asynchronous data reception. The clock recovery logic is used for synchronizing the internally generated baud rate clock to the incoming asynchronous serial frames at the RxD pin. The data recovery logic samples and low pass filters each incoming bit, thereby improving the noise immunity of the Receiver. The asynchronous reception operational range depends on the accuracy of the internal baud rate clock, the rate of the incoming frames, and the frame size in number of bits. The clock recovery logic synchronizes internal clock to the incoming serial frames. Figure 49 illustrates the sampling process of the start bit of an incoming frame. The sample rate is 16 times the baud rate for normal mode, and 8 times the baud rate for Double Speed mode. The horizontal arrows illustrate the synchronization variation due to the sampling process. Note the larger time variation when using the double speed mode (U2X = 1) of operation. Samples denoted zero are samples done when the RxD line is idle (i.e. no communication activity). Figure 49. Start Bit Sampling
RxD IDLE START BIT 0
Asynchronous Clock Recovery
Sample
(U2X = 0) 0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1 2 3
Sample
(U2X = 1) 0 1 2 3 4 5 6 7 8 1 2
When the clock recovery logic detects a high (idle) to low (start) transition on the RxD line, the start bit detection sequence is initiated. Let sample 1 denote the first zero-sample as shown in the figure. The clock recovery logic then uses samples 8, 9 and 10 for Normal mode, and samples 4, 5 and 6 for Double Speed mode (indicated with sample numbers inside boxes on the figure), to decide if a valid start bit is received. If two or more of these three samples have logical high levels (the majority wins), the start bit is rejected as a noise spike and the Receiver starts looking for the next high to low-transition. If however, a valid start bit is detected, the clock recovery logic is synchronized and the data recovery can begin. The synchronization process is repeated for each start bit. Asynchronous Data Recovery When the Receiver clock is synchronized to the start bit, the data recovery can begin. The data recovery unit uses a state machine that has 16 states for each bit in Normal mode and 8 states for each bit in Double Speed mode. Figure 50 shows the sampling of the data bits and the parity bit. Each of the samples is given a number that is equal to the state of the recovery unit. Figure 50. Sampling of Data and Parity Bit
RxD BIT n
Sample
(U2X = 0) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1
Sample
(U2X = 1) 1 2 3 4 5 6 7 8 1
88
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
The decision of the logic level of the received bit is taken by doing a majority voting of the logic value to the three samples in the center of the received bit. The center samples are emphasized on the figure by having the sample number inside boxes. The majority voting process is done as follows: If two or all three samples have high levels, the received bit is registered to be a logic 1. If two or all three samples have low levels, the received bit is registered to be a logic 0. This majority voting process act as a low pass filter for the incoming signal on the RxD pin. The recovery process is then repeated until a complete frame is received. Including the first stop bit. Note that the Receiver only uses the first stop bit of a frame. Figure 51 shows the sampling of the stop bit and the earliest possible beginning of the start bit of the next frame. Figure 51. Stop Bit Sampling and Next Start Bit Sampling
RxD STOP 1
(A) (B) (C)
Sample
(U2X = 0) 1 2 3 4 5 6 7 8 9 10 0/1 0/1 0/1
Sample
(U2X = 1) 1 2 3 4 5 6 0/1
The same majority voting is done to the stop bit as done for the other bits in the frame. If the stop bit is registered to have a logic 0 value, the Frame Error (FE) Flag will be set. A new high to low transition indicating the start bit of a new frame can come right after the last of the bits used for majority voting. For normal speed mode, the first low level sample can be at point marked (A) in Figure 51. For double speed mode the first low level must be delayed to (B). (C) marks a stop bit of full length. The early start bit detection influences the operational range of the Receiver. Asynchronous Operational Range The operational range of the Receiver is dependent of the mismatch between the received bit rate and the internally generated baud rate. If the Transmitter is sending frames at too fast or too slow bit rates, or the internally generated baud rate of the Receiver does not have exact base frequency, the Receiver will not be able to synchronize the frames to the start bit. The following equations can be used to calculate the ratio of the incoming data rate and internal Receiver baud rate.
( D + 1 )S R slow = -----------------------------------------S - 1 + D S + SF D S SF SM
( D + 2 )S R fast = ----------------------------------( D + 1 )S + S M
Sum of character size and parity size (D = 5 to 10 bit). Samples per bit. S = 16 for Normal Speed mode and S = 8 for Double Speed mode. First sample number used for majority voting. SF = 8 for Normal Speed and SF = 4 for Double Speed mode. Middle sample number used for majority voting. SM = 9 for Normal Speed and SM = 5 for Double Speed mode.
89
1457G-AVR-09/03
Rslow is the ratio of the slowest incoming data rate that can be accepted in relation to the Receiver baud rate. Rfast is the ratio of the fastest incoming data rate that can be accepted in relation to the Receiver baud rate. Table 30 and Table 31 list the maximum Receiver baud rate error that can be tolerated. Note that normal speed mode has higher toleration of baud rate variations. Table 30. Recommended Maximum Receiver Baud Rate Error for Normal Speed Mode (U2X = 0)
D# (Data+Parity Bit) 5 6 7 8 9 10 Rslow (%) 93.20 94.12 94.81 95.36 95.81 96.17 Rfast (%) 106.67 105.79 105.11 104.58 104.14 103.78 Max Total Error (%) +6.67/-6.8 +5.79/-5.88 +5.11/-5.19 +4.58/-4.54 +4.14/-4.19 +3.78/-3.83 Recommended Max Receiver Error (%) 3.0 2.5 2.0 2.0 1.5 1.5
Table 31. Recommended Maximum Receiver Baud Rate Error for Double Speed Mode (U2X = 1)
D # (Data+Parity Bit) 5 6 7 8 9 10 Max Total Error (%) +5.66/-5.88 +4.92/-5.08 +4.35/-4.48 +3.90/-4.00 +3.53/-3.61 +3.23/-3.30 Recommended Max Receiver Error (%) 2.5 2.0 1.5 1.5 1.5 1.0
Rslow (%) 94.12 94.92 95.52 96.00 96.39 96.70
Rfast (%) 105.66 104.92 104.35 103.90 103.53 103.23
The recommendations of the maximum Receiver baud rate error was made under the assumption that the Receiver and Transmitter equally divides the maximum total error. There are two possible sources for the Receivers baud rate error. The Receiver's system clock (XTAL) will always have some minor instability over the supply voltage range and the temperature range. When using a crystal to generate the system clock, this is rarely a problem, but for a resonator the system clock may differ more than 2% depending of the resonators tolerance. The second source for the error is more controllable. The baud rate generator can not always do an exact division of the system frequency to get the baud rate wanted. In this case an UBRR value that gives an acceptable low error can be used if possible.
90
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Multi-processor Communication Mode
Setting the Multi-Processor Communication mode (MPCM) bit in UCSRA enables a filtering function of incoming frames received by the USART Receiver. Frames that do not contain address information will be ignored and not put into the receive buffer. This effectively reduces the number of incoming frames that has to be handled by the CPU, in a system with multiple MCUs that communicate via the same serial bus. The Transmitter is unaffected by the MPCM setting, but has to be used differently when it is a part of a system utilizing the Multi-processor Communication mode. If the Receiver is set up to receive frames that contain 5 to 8 data bits, then the first stop bit indicates if the frame contain data or address information. If the Receiver is set up for frames with 9 data bits, then the ninth bit (RXB8) is used for identifying address and data frames. When the frame type bit (the first stop or the ninth bit) is one, the frame contains an address. When the frame type bit is zero the frame is a data frame. The Multi-processor Communication mode enables several Slave MCUs to receive data from a Master MCU. This is done by first decoding an address frame to find out which MCU has been addressed. If a particular Slave MCU has been addressed, it will receive the following data frames as normal, while the other Slave MCUs will ignore the received frames until another address frame is received. Using MPCM For an MCU to act as a Master MCU, it can use a 9-bit character frame format (UCSZ = 7). The ninth bit (TXB8) must be set when an address frame (TXB8 = 1) or cleared when a data frame (TXB = 0) is being transmitted. The Slave MCUs must in this case be set to use a 9-bit character frame format. The following procedure should be used to exchange data in Multi-processor Communication mode: 1. All Slave MCUs are in Multi-processor Communication mode (MPCM in UCSRA is set). 2. The Master MCU sends an address frame, and all Slaves Receive and read this frame. In the Slave MCUs, the RXC Flag in UCSRA will be set as normal. 3. Each Slave MCU reads the UDR Register and determines if it has been selected. If so, it clears the MPCM bit in UCSRA, otherwise it waits for the next address byte and keeps the MPCM setting. 4. The addressed MCU will receive all data frames until a new address frame is received. The other Slave MCUs, which still have the MPCM bit set, will ignore the data frames. 5. When the last data frame is received by the addressed MCU, the addressed MCU sets the MPCM bit and waits for a new address frame from Master. The process then repeats from 2. Using any of the 5- to 8-bit character frame formats is possible, but impractical since the Receiver must change between using n and n+1 character frame formats. This makes full-duplex operation difficult since the Transmitter and Receiver uses the same character size setting. If 5- to 8-bit character frames are used, the Transmitter must be set to use two stop bit (USBS = 1) since the first stop bit is used for indicating the frame type. Do not use Read-Modify-Write instructions (SBI and CBI) to set or clear the MPCM bit. The MPCM bit shares the same I/O location as the TXC Flag and this might accidentally be cleared when using SBI or CBI instructions.
91
1457G-AVR-09/03
Accessing UBRRH/UCSRC Registers
Write Access
The UBRRH Register shares the same I/O location as the UCSRC Register. Therefore some special consideration must be taken when accessing this I/O location.
When doing a write access of this I/O location, the high bit of the value written, the USART Register Select (URSEL) bit, controls which one of the two registers that will be written. If URSEL is zero during a write operation, the UBRRH value will be updated. If URSEL is one, the UCSRC setting will be updated. The following code examples show how to access the two registers. Assembly Code Examples(1)
... ; Set UBRRH to 2 ldi r16,0x02 out UBRRH,r16 ... ; Set the USBS and the UCSZ1 bit to one, and ; the remaining bits to zero. ldi r16,(1<C Code Examples(1)
... /* Set UBRRH to 2 */ UBRRH = 0x02; ... /* Set the USBS and the UCSZ1 bit to one, and */ /* the remaining bits to zero. */ UCSRC = (1<Note:
1. The example code assumes that the part specific header file is included.
As the code examples illustrate, write accesses of the two registers are relatively unaffected of the sharing of I/O location.
92
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Read Access Doing a read access to the UBRRH or the UCSRC Register is a more complex operation. However, in most applications, it is rarely necessary to read any of these registers. The read access is controlled by a timed sequence. Reading the I/O location once returns the UBRRH Register contents. If the register location was read in previous system clock cycle, reading the register in the current clock cycle will return the UCSRC contents. Note that the timed sequence for reading the UCSRC is an atomic operation. Interrupts must therefore be disabled during the read operation. The following code example shows how to read the UCSRC Register contents. Assembly Code Example(1)
USART_ReadUCSRC: ; Save Global Interrupt Flag in r17,SREG
; Disable interrupts cli ; Read UCSRC in in r16,UBRRH r16,UCSRC
; Restore Global Interrupt Flag out SREG,r17 ret
C Code Example(1)
unsigned char USART_ReadUCSRC( void ) { unsigned char sreg, ucsrc; /* Save Global Interrupt Flag */ sreg = SREG; /* Disable interrupts */ _CLI(); /* Read UCSRC */ ucsrc = UBRRH; ucsrc = UCSRC; /* Restore Global Interrupt Flag */ SREG = sreg; return ucsrc; }
Note:
1. The example code assumes that the part specific header file is included.
The assembly code example returns the UCSRC value in r16. Reading the UBRRH contents is not an atomic operation and therefore it can be read as an ordinary register, as long as the previous instruction did not access the register location.
93
1457G-AVR-09/03
USART Register Description
USART I/O Data Register - UDR
Bit $0C ($2C) Read $0C ($2C) Write Read/Write Initial Value
7
6
5
4 RXB[7:0] TXB[7:0]
3
2
1
0 UDR (Read) UDR (Write)
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
The USART Transmit Data Buffer Register and USART Receive Data Buffer Registers share the same I/O address referred to as USART Data Register or UDR. The Transmit Data Buffer Register (TXB) will be the destination for data written to the UDR Register location. Reading the UDR Register location will return the contents of the Receive Data Buffer Register (RXB). For 5-, 6-, or 7-bit characters the upper unused bits will be ignored by the Transmitter and set to zero by the Receiver. The transmit buffer can only be written when the UDRE Flag in the UCSRA Register is set. Data written to UDR when the UDRE Flag is not set, will be ignored by the USART Transmitter. When data is written to the transmit buffer, and the Transmitter is enabled, the Transmitter will load the data into the Transmit Shift Register when the Shift Register is empty. Then the data will be serially transmitted on the TxD pin. The Receive Buffer consists of a two level FIFO. The FIFO will change its state whenever the Receive Buffer is accessed. Due to this behavior of the receive buffer, do not use Read-Modify-Write instructions (SBI and CBI) on this location. Be careful when using bit test instructions (SBIC and SBIS), since these also will change the state of the FIFO. USART Control and Status Register A - UCSRA
Bit $0B ($2B) Read/Write Initial Value
7 RXC R 0
6 TXC R/W 0
5 UDRE R 1
4 FE R 0
3 DOR R 0
2 PE R 0
1 U2X R/W 0
0 MPCM R/W 0 UCSRA
* Bit 7 - RXC: USART Receive Complete This flag bit is one when there are unread data in the receive buffer and zero when the receive buffer is empty (i.e., does not contain any unread data). If the Receiver is disabled, the receive buffer will be flushed and consequently the RXC bit will become zero. The RXC Flag can be used to generate a Receive Complete interrupt (see description of the RXCIE bit). * Bit 6 - TXC: USART Transmit Complete This flag bit is set one when the entire frame in the Transmit Shift Register has been shifted out and there are no new data currently present in the transmit buffer (UDR). The TXC Flag bit is automatically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. The TXC Flag can generate a Transmit Complete interrupt (see description of the TXCIE bit).
94
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
* Bit 5 - UDRE: USART Data Register Empty The UDRE Flag indicates if the transmit buffer (UDR) is ready to receive new data. If UDRE is one the buffer is empty and therefore ready be written. The UDRE Flag can generate a Data Register Empty interrupt (see description of the UDRIE bit). UDRE is set (one) after a reset to indicate that the Transmitter is ready. * Bit 4 - FE: Frame Error This bit is set if the next character in the receive buffer had a Frame Error when received. I.e. when the first stop bit of the next character in the receive buffer is zero. This bit is valid until the receive buffer (UDR) is read. The FE bit is zero when the stop bit of received data is one. Always set this bit to zero when writing to UCSRA. * Bit 3 - DOR: Data OverRun This bit is set if a Data OverRun condition is detected. A Data OverRun occur when the receive buffer is full (two characters), it is a new character waiting in the Receive Shift Register, and a new start bit is detected. Always set this bit to zero when writing to UCSRA. * Bit 2 - PE: Parity Error This bit is set if the next character in the receive buffer had a Parity Error when received and the parity checking was enabled at that point (UPM1 = 1). This bit is valid until the Receive Buffer (UDR) is read. Always set this bit to zero when writing to UCSRA. * Bit 1 - U2X: Double the USART Transmission Speed Setting this bit only has effect for the asynchronous operation. Set this bit to zero when using synchronous operation. Setting this bit will reduce the divisor of the baud rate divider from 16 to 8 effectively doubling the transfer rate for asynchronous communication. * Bit 0 - MPCM: Multi-processor Communication Mode Setting this bit enables the Multi-processor Communication mode. When the MPCM bit is set, all the incoming frames received by the USART Receiver that do not contain address information will be ignored. The Transmitter is unaffected by the MPCM setting. For more detailed information see "Multi-processor Communication Mode" on page 91.
95
1457G-AVR-09/03
USART Control and Status Register B - UCSRB
Bit $0A ($2A) Read/Write Initial Value
7 RXCIE R/W 0
6 TXCIE R/W 0
5 UDRIE R/W 0
4 RXEN R/W 0
3 TXEN R/W 0
2 UCSZ2 R/W 0
1 RXB8 R 0
0 TXB8 W 0 UCSRB
* Bit 7 - RXCIE: RX Complete Interrupt Enable Setting this bit to one enables interrupt on the RXC Flag. A USART Receive Complete interrupt will be generated only if the RXCIE bit is set, the Global Interrupt Flag in SREG is set and the RXC bit in UCSRA is set. * Bit 6 - TXCIE: TX Complete Interrupt Enable Setting this bit to one enables interrupt on the TXC Flag. A USART Transmit Complete interrupt will be generated only if the TXCIE bit is set, the Global Interrupt Flag in SREG is set and the TXC bit in UCSRA is set. * Bit 5 - UDRIE: USART Data Register Empty Interrupt Enable Setting this bit to one enables interrupt on the UDRE Flag. A Data Register Empty Interrupt will be generated only if the UDRIE bit is set, the Global Interrupt Flag in SREG is set and the UDRE bit in UCSRA is set. * Bit 4 - RXEN: Receiver Enable Setting this bit to one enables the USART Receiver. The Receiver will override normal port operation for the RxD pin when enabled. Disabling the Receiver will flush the Receive Buffer invalidating the FE, DOR, and PE Flags. * Bit 3 - TXEN: Transmitter Enable Setting this bit to one enables the USART Transmitter. The Transmitter will override normal port operation for the TxD pin when enabled. The disabling of the Transmitter (setting the TXEN to zero) will not become effective until ongoing and pending transmissions are completed, i.e. when the Transmit Shift Register and Transmit Buffer Register does not contain data to be transmitted. When disabled the Transmitter will no longer override the TxD port. * Bit 2 - UCSZ2: Character Size The UCSZ2 bits combined with the UCSZ1:0 bit in UCSRC sets the number of data bits (character size) in a frame the Receiver and Transmitter use. * Bit 1 - RXB8: Receive Data Bit 8 RXB8 is the ninth data bit of the received character when operating with serial frames with nine data bits. Must be read before reading the low bits from UDR. * Bit 0 - TXB8: Transmit Data Bit 8 TXB8 is the ninth data bit in the character to be transmitted when operating with serial frames with nine data bits. Must be written before writing the low bits to UDR.
96
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
USART Control and Status Register C - UCSRC
Bit $20 ($40) Read/Write Initial Value
7 URSEL R/W 1
6 UMSEL R/W 0
5 UPM1 R/W 0
4 UPM0 R/W 0
3 USBS R/W 0
2 UCSZ1 R/W 1
1 UCSZ0 R/W 1
0 UCPOL R/W 0 UCSRC
The UCSRC Register shares the same I/O location as the UBRRH Register. See the "Accessing UBRRH/UCSRC Registers" on page 92 section which describes how to access this register. * Bit 7 - URSEL: Register Select This bit selects between accessing the UCSRC or the UBRRH Register. It is read as one when reading UCSRC. The URSEL must be one when writing the UCSRC. * Bit 6 - UMSEL: USART Mode Select This bit selects between asynchronous and synchronous mode of operation. Table 32. USART Mode
UMSEL 0 1 Mode Asynchronous Operation Synchronous Operation
* Bit 5:4 - UPM1:0: Parity Mode This bit enable and set type of parity generation and check. If enabled, the Transmitter will automatically generate and send the parity of the transmitted data bits within each frame. The Receiver will generate a parity value for the incoming data and compare it to the UPM0 setting. If a mismatch is detected, the PE Flag in UCSRA will be set. Table 33. Parity Mode
UPM1 0 0 1 1 UPM0 0 1 0 1 Parity Mode Disabled (Reserved) Enabled, Even Parity Enabled, Odd Parity
* Bit 3 - USBS: Stop Bit Select This bit selects number of stop bits to be inserted by the Transmitter. The Receiver ignores this setting. Table 34. Stop Bit Select
USBS 0 1 Stop Bit(s) 1-bit 2-bit
97
1457G-AVR-09/03
* Bit 2:1 - UCSZ1:0: Character Size The UCSZ1:0 bits combined with the UCSZ2 bit in UCSRB sets the number of data bits (character size) in a frame the Receiver and Transmitter uses. Table 35. Character Size
UCSZ2 0 0 0 0 1 1 1 1 UCSZ1 0 0 1 1 0 0 1 1 UCSZ0 0 1 0 1 0 1 0 1 Character Size 5-bit 6-bit 7-bit 8-bit Reserved Reserved Reserved 9-bit
* Bit 0 - UCPOL: Clock Polarity This bit is used for synchronous mode only. Set this bit to zero when asynchronous mode is used. The UCPOL bit sets the relationship between data output change and data input sample, and the synchronous clock (XCK).
Transmitted Data Changed (Output of TxD Pin) Falling XCK Edge Rising XCK Edge Received Data Sampled (Input on RxD Pin) Rising XCK Edge Falling XCK Edge
UCPOL 0 1
USART Baud Rate Registers - UBRRL and UBRRHs
Bit $20 ($40) $09 ($29)
15 URSEL
14 -
13 -
12 -
11
10
9
8 UBRRH UBRRL
UBRR[11:8]
UBRR[7:0] 7 6 R R/W 0 0 5 R R/W 0 0 4 R R/W 0 0 3 R/W R/W 0 0 2 R/W R/W 0 0 1 R/W R/W 0 0 0 R/W R/W 0 0
Read/Write
R/W R/W
Initial Value
0 0
The UBRRH Register shares the same I/O location as the UCSRC Register. See the "Accessing UBRRH/UCSRC Registers" on page 92 section which describes how to access this register. * Bit 15 - URSEL: Register Select This bit selects between accessing the UBRRH or the UCSRC Register. It is read as zero when reading UBRRH. The URSEL must be zero when writing the UBRRH. * Bit 14:12 - Reserved Bits These bits are reserved for future use. For compatibility with future devices, these bit must be set to zero when UBRRH is written.
98
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
* Bit 11:0 - UBRR11:0: USART Baud Rate Register This is a 12-bit register which contains the USART baud rate. The UBRRH contains the four most significant bits, and the UBRRL contains the eight least significant bits of the USART baud rate. Ongoing transmissions by the Transmitter and Receiver will be corrupted if the baud rate is changed. Writing UBRRL will trigger an immediate update of the baud rate prescaler.
Examples of Baud Rate Setting
For standard crystal and resonator frequencies, the most commonly used baud rates for asynchronous operation can be generated by using the UBRR settings in Table 36. UBRR values which yield an actual baud rate differing less than 0.5% from the target baud rate, are bold in the table. Higher error ratings are acceptable, but the Receiver will have less noise resistance when the error ratings are high, especially for large serial frames (see "Asynchronous Operational Range" on page 89). The error values are calculated using the following equation:
BaudRateClosest Match Error[%] = ------------------------------------------------------- - 1 * 100% BaudRate

Table 36. Examples of UBRR Settings for Commonly Used Oscillator Frequencies -
UBRR = 0, Error = 0.0% fosc = 1.0000 MHz Baud Rate (bps) 2400 4800 9600 14.4K 19.2K 28.8K 38.4K 57.6K 76.8K 115.2K 230.4K 250K Max Baud Rate (bps) 2400 4800 9600 U2X = 0 UBRR 25 12 6 3 2 1 1 0 - - - -
62.5 Kbps
fosc = 1.8432 MHz U2X = 0 UBRR 47 23 11 7 5 3 2 1 1 0 - - Error 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% -25.0% 0.0% - - U2X = 1 UBRR 95 47 23 15 11 7 5 3 2 1 0 - Error 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% -
U2X = 1 UBRR 51 25 12 8 6 3 2 1 1 0 - -
125 Kbps
Error 0.2% 0.2% -7.0% 8.5% 8.5% 8.5% -18.6% 8.5% - - - -
Error 0.2% 0.2% 0.2% -3.5% -7.0% 8.5% 8.5% 8.5% -18.6% 8.5% - -
115.2 Kbps
230.4 Kbps
fosc = 2.0000 MHz U2X = 0 UBRR Error U2X = 1 UBRR Error
fosc = 3.6864 MHz U2X = 0 UBRR Error U2X = 1 UBRR Error
51 25 12
0.2% 0.2% 0.2%
103 51 25
0.2% 0.2% 0.2%
95 47 23
0.0% 0.0% 0.0%
191 95 47
0.0% 0.0% 0.0%
99
1457G-AVR-09/03
Table 36. Examples of UBRR Settings for Commonly Used Oscillator Frequencies - UBRR = 0, Error = 0.0% (Continued)
14.4K 19.2K 28.8K 38.4K 57.6K 76.8K 115.2K 230.4K 250K 1M Max Baud Rate (bps) 2400 4800 9600 14.4K 19.2K 28.8K 38.4K 57.6K 76.8K 115.2K 230.4K 250K 0.5M 1M Max Baud Rate (bps) 2400 4800 9600 14.4K 125 Kbps 250 Kbps 8 6 3 2 1 1 0 - - -3.5% -7.0% 8.5% 8.5% 8.5% -18.6% 8.5% - - 16 12 8 6 3 2 1 - 0 2.1% 0.2% -3.5% -7.0% 8.5% 8.5% 8.5% - 0.0% 15 11 7 5 3 2 1 0 0 - 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% -7.8% - 31 23 15 11 7 5 3 1 1 0 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% -7.8% -7.8%
230.4 Kbps
460.8 Kbps
fosc = 4.0000 MHz U2X = 0 UBRR 103 51 25 16 12 8 6 3 2 1 0 0 - - Error 0.2% 0.2% 0.2% 2.1% 0.2% -3.5% -7.0% 8.5% 8.5% 8.5% 8.5% 0.0% - - U2X = 1 UBRR 207 103 51 34 25 16 12 8 6 3 1 1 0 - Error 0.2% 0.2% 0.2% -0.8% 0.2% 2.1% 0.2% -3.5% -7.0% 8.5% 8.5% 0.0% 0.0% -
fosc = 7.3728 MHz U2X = 0 UBRR 191 95 47 31 23 15 11 7 5 3 1 1 0 - Error 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% -7.8% -7.8% - U2X = 1 UBRR 383 191 95 63 47 31 23 15 11 7 3 3 1 0 Error 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% 0.0% -7.8% -7.8% -7.8%
250 Kbps
0.5 Mbps
460.8 Kpbs
921.6 Kbps
fosc = 8.0000 MHz U2X = 0 UBRR 207 103 51 34 Error 0.2% 0.2% 0.2% -0.8% U2X = 1 UBRR 416 207 103 68 Error -0.1% 0.2% 0.2% 0.6%
100
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Table 36. Examples of UBRR Settings for Commonly Used Oscillator Frequencies - UBRR = 0, Error = 0.0% (Continued)
19.2K 28.8K 38.4K 57.6K 76.8K 115.2K 230.4K 250K 0.5M 1M Max 25 16 12 8 6 3 1 1 0 - 0.2% 2.1% 0.2% -3.5% -7.0% 8.5% 8.5% 0.0% 0.0% - 51 34 25 16 12 8 3 3 1 0 0.2% -0.8% 0.2% 2.1% 0.2% -3.5% 8.5% 0.0% 0.0% 0.0% 1 Mbps
0.5 Mbps
101
1457G-AVR-09/03
Two-wire Serial Interface (Byte Oriented)
The Two-wire Serial Interface supports bi-directional serial communication. It is designed primarily for simple but efficient integrated circuit (IC) control. The system is comprised of two lines, SCL (Serial Clock) and SDA (Serial Data) that carry information between the ICs connected to them. Various communication configurations can be designed using this bus. Figure 52 shows a typical Two-wire Serial Bus configuration. Any device connected to the bus can be Master or Slave. Note that all AVR devices connected to the bus must be powered to allow any bus operation. Figure 52. Two-wire Serial Bus Configuration
V
CC
Device 1
Device 2
Device 3 ....... Device n
R1
R2
SCL SDA
The Two-wire Serial Interface supports Master/Slave and Transmitter/Receiver operation at up to 400 kHz bus clock rate. The Two-wire Serial Interface has hardware support for 7-bit addressing. When the Two-wire Serial Interface is enabled (TWEN in TWCR is set), a glitch filter is enabled for the input signals from the pins PC0 (SCL) and PC1 (SDA), and the output from these pins is slew-rate controlled. The Two-wire Serial Interface is byte oriented. The operation of the Two-wire Serial Bus is shown as a pulse diagram in Figure 53, including the START and STOP conditions and generation of ACK signal by the bus Receiver. Figure 53. Two-wire Serial Bus Timing Diagram
ACKNOWLEDGE FROM RECEIVER SDA MSB R/W BIT STOP CONDITION REPEATED START CONDIT
SCL START CONDITION
1
2
7
8
9 ACK
1
2
8
9 ACK
The block diagram of the Two-wire Serial Interface is shown in Figure 54.
102
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Figure 54. Block diagram of the Two-wire Serial Interface
ADDRESS REGISTER AND COMPARATOR TWAR
INPUT SDA OUTPUT
DATA SHIFT REGISTER TWDR
ACK
INPUT SCL OUTPUT
START/STOP AND SYNC ARBITRATION
TIMING AND CONTROL
SERIAL CLOCK GENERATOR STATUS
CONTROL REGISTER TWCR
STATE MACHINE AND STATUS DECODER
STATUS REGISTER TWSR
The CPU interfaces with the Two-wire Serial Interface via the following five I/O Registers: the Two-wire Serial Interface Bit Rate Register (TWBR), the Two-wire Serial Interface Control Register (TWCR), the Two-wire Serial Interface Status Register (TWSR), the Two-wire Serial Interface Data Register (TWDR), and the Two-wire Serial Interface Address Register (TWAR, used in Slave mode).
AVR 8-BIT DATA BUS
103
1457G-AVR-09/03
The Two-wire Serial Interface Bit Rate Register - TWBR
Bit $00 ($20) Read/Write Initial Value
7 TWBR7 R/W 0
6 TWBR6 R/W 0
5 TWBR5 R/W 0
4 TWBR4 R/W 0
3 TWBR3 R/W 0
2 TWBR2 R/W 0
1 TWBR1 R/W 0
0 TWBR0 R/W 0 TWBR
* Bits 7..0 - Two-wire Serial Interface Bit Rate Register TWBR selects the division factor for the bit rate generator. The bit rate generator is a frequency divider which generates the SCL clock frequency in the Master modes according to the following equation: f CK Bit Rate = ---------------------------------------------------------16 + 2(TWBR) + t A f CK Bit Rate = SCL frequency fCK TWBR tA = CPU Clock frequency = Contents of the Two-wire Serial Interface Bit Rate Register = Bus alignment adjustment
Both the Receiver and the Transmitter can stretch the low period of the SCL line when waiting for user response, thereby reducing the average bit rate.
* * * *
Note:
TWBR should be set to a value higher than seven to ensure correct Two-wire Serial Bus functionality. The bus alignment adjustment is automatically inserted by the Two-wire Serial Interface, and ensures the validity of setup and hold times on the bus for any TWBR value higher than 7. This adjustment may vary from 200 ns to 600 ns depending on bus loads and drive capabilities of the devices connected to the bus. The Two-wire Serial Interface Control Register - TWCR
Bit $36 ($56) Read/Write Initial Value
7 TWINT R/W 0
6 TWEA R/W 0
5 TWSTA R/W 0
4 TWSTO R/W 0
3 TWWC R 0
2 TWEN R/W 0
1 - R 0
0 TWIE R/W 0 TWCR
* Bit 7 - TWINT: Two-wire Serial Interface Interrupt Flag This bit is set by hardware when the Two-wire Serial Interface has finished its current job and expects application software response. If the I-bit in the SREG and TWIE in the TWCR Register are set (one), the MCU will jump to the Interrupt Vector at address $026. While the TWINT Flag is set, the bus SCL clock line low period is stretched. The TWINT Flag must be cleared by software by writing a logic one to it. Note that this flag is not automatically cleared by hardware when executing the interrupt routine. Also note that clearing this flag starts the operation of the Two-wire Serial Interface, so all accesses to the Two-wire Serial Interface Address Register - TWAR, Two-wire Serial Interface Status Register - TWSR, and Two-wire Serial Interface Data Register - TWDR must be complete before clearing this flag. * Bit 6 - TWEA: Two-wire Serial Interface Enable Acknowledge Flag TWEA Flag controls the generation of the acknowledge pulse. If the TWEA bit is set, the ACK pulse is generated on the Two-wire Serial Bus if the following conditions are met: 1. The device's own slave address has been received. 2. A general call has been received, while the TWGCE bit in the TWAR is set. 3. A data byte has been received in Master Receiver or Slave Receiver mode.
104
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
By setting the TWEA bit low, the device can be virtually disconnected from the Two-wire Serial Bus temporarily. Address recognition can then be resumed by setting the TWEA bit again. * Bit 5 - TWSTA: Two-wire Serial Bus START Condition Flag The TWSTA Flag is set by the application when it desires to become a Master on the Two-wire Serial Bus. The Two-wire Serial Interface hardware checks if the bus is available, and generates a START condition on the bus if it is free. However, if the bus is not free, the Two-wire Serial Interface waits until a STOP condition is detected, and then generates a new START condition to claim the bus Master status. * Bit 4 - TWSTO: Two-wire Serial Bus STOP Condition Flag TWSTO is a Stop Condition Flag. In Master mode setting the TWSTO bit in the Control Register will generate a STOP condition on the Two-wire Serial Bus. When the STOP condition is executed on the bus, the TWSTO bit is cleared automatically. In Slave mode setting the TWSTO bit can be used to recover from an error condition. No stop condition is generated on the bus then, but the Two-wire Serial Interface returns to a well-defined unaddressed Slave mode and releases the SCL and SDA lines to a high impedance state. * Bit 3 - TWWC: Two-wire Serial Bus Write Collision Flag The TWWC bit is set when attempting to write to the Two-wire Serial Interface Data Register - TWDR when TWINT is low. This flag is cleared by writing the TWDR Register when TWINT is high. * Bit 2 - TWEN: Two-wire Serial Interface Enable Bit The TWEN bit enables Two-wire Serial Interface operation. If this bit is cleared (zero), the bus outputs SDA and SCL are set to high impedance state, and the input signals are ignored. The interface is activated by setting this bit (one). * Bit 1 - Res: Reserved Bit This bit is a reserved bit in the ATmega323 and will always read as zero. * Bit 0 - TWIE: Two-wire Serial Interface Interrupt Enable When this bit is enabled, and the I-bit in SREG is set, the Two-wire Serial Interface interrupt will be activated for as long as the TWINT Flag is high. The TWCR is used to control the operation of the Two-wire Serial Interface. It is used to enable the Two-wire Serial Interface, to initiate a Master access by applying a START condition to the bus, to generate a Receiver acknowledge, to generate a stop condition, and to control halting of the bus while the data to be written to the bus are written to the TWDR. It also indicates a write collision if data is attempted written to TWDR while the register is inaccessible.
105
1457G-AVR-09/03
The Two-wire Serial Interface Status Register - TWSR
Bit $01 ($21) Read/Write Initial Value
7 TWS7 R 1
6 TWS6 R 1
5 TWS5 R 1
4 TWS4 R 1
3 TWS3 R 1
2 - R 0
1 - R 0
0 - R 0 TWSR
* Bits 7..3 - TWS: Two-wire Serial Interface Status These five bits reflect the status of the Two-wire Serial Interface logic and the Two-wire Serial Bus. * Bits 2..0 - Res: Reserved bits These bits are reserved in ATmega323 and will always read as zero The TWSR is read only. It contains a status code which reflects the status of the Twowire Serial Interface logic and the Two-wire Serial Bus. There are 26 possible status codes. When TWSR contains $F8, no relevant state information is available and no Two-wire Serial Interface interrupt is requested. A valid status code is available in TWSR one CPU clock cycle after the Two-wire Serial Interface Interrupt Flag (TWINT) is set by hardware and is valid until one CPU clock cycle after TWINT is cleared by software. Table 37 to Table 44 give the status information for the various modes. The Two-wire Serial Interface Data Register - TWDR
Bit $03 ($23) Read/Write Initial Value
7 TWD7 R/W 1
6 TWD6 R/W 1
5 TWD5 R/W 1
4 TWD4 R/W 1
3 TWD3 R/W 1
2 TWD2 R/W 1
1 TWD1 R/W 1
0 TWD0 R/W 1 TWDR
* Bits 7..0 - TWD: Two-wire Serial Interface Data Register These eight bits constitute the next data byte to be transmitted, or the latest data byte received on the Two-wire Serial Bus. In Transmit mode, TWDR contains the next byte to be transmitted. In Receive mode, the TWDR contains the last byte received. It is writable while the Two-wire Serial Interface is not in the process of shifting a byte. This occurs when the Two-wire Serial Interface Interrupt Flag (TWINT) is set by hardware. Note that the Data Register cannot be initialized by the user before the first interrupt occurs. The data in TWDR remain stable as long as TWINT is set. While data is shifted out, data on the bus is simultaneously shifted in. TWDR always contains the last byte present on the bus, except after a wake up from ADC Noise Reduction mode, Power-down mode, or Power-save mode by the Two-wire Serial Interface interrupt. For example, in the case of a lost bus arbitration, no data is lost in the transition from Master to Slave. Handling of the ACK Flag is controlled automatically by the Two-wire Serial Interface logic, the CPU cannot access the ACK bit directly.
106
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
The Two-wire Serial Interface (Slave) Address Register - TWAR
Bit $02 ($22) Read/Write Initial Value
7 TWA6 R/W 1
6 TWA5 R/W 1
5 TWA4 R/W 1
4 TWA3 R/W 1
3 TWA2 R/W 1
2 TWA1 R/W 1
1 TWA0 R/W 1
0 TWGCE R/W 0 TWAR
* Bits 7..1 - TWA: Two-wire Serial Interface (Slave) Address Register These seven bits constitute the slave address of the Two-wire Serial Bus unit. * Bit 0 - TWGCE: Two-wire Serial Interface General Call Recognition Enable bit This bit enables, if set, the recognition of the General Call given over the Two-wire Serial Bus. The TWAR should be loaded with the 7-bit slave address (in the seven most significant bits of TWAR) to which the Two-wire Serial Interface will respond when programmed as a Slave Transmitter or Receiver, and not needed in the Master modes. The LSB of TWAR is used to enable recognition of the general call address ($00). There is an associated address comparator that looks for the slave address (or general call address if enabled) in the received serial address. If a match is found, an interrupt request is generated.
Two-wire Serial Interface Modes
The Two-wire Serial Interface can operate in four different modes: * * * * Master Transmitter Master Receiver Slave Receiver Slave Transmitter
Data transfer in each mode of operation is shown in Figure 55 to Figure 58. These figures contain the following abbreviations: S: START condition R: Read bit (high level at SDA) W: Write bit (low level at SDA) A: Acknowledge bit (low level at SDA) A: Not acknowledge bit (high level at SDA) Data: 8-bit data byte P: STOP condition SLA: Slave Address In Figure 55 to Figure 58, circles are used to indicate that the Two-wire Serial Interface Interrupt Flag is set. The numbers in the circles show the status code held in TWSR. At these points, actions must be taken by the application to continue or complete the Twowire Serial Bus transfer. The Two-wire Serial Bus transfer is suspended until the Twowire Serial Interface Interrupt Flag is cleared by software. The Two-wire Serial Interface Interrupt Flag is not automatically cleared by hardware when executing the interrupt routine. Software has to clear the flag to continue the Twowire transfer. Also note that the Two-wire Serial Interface starts execution as soon as this bit is cleared, so that all access to TWAR, TWDR, and TWSR must have been completed before clearing this flag.
107
1457G-AVR-09/03
When the Two-wire Serial Interface Interrupt Flag is set, the status code in TWSR is used to determine the appropriate software action. For each status code, the required software action and details of the following serial transfer are given in Table 37 to Table 44.
Master Transmitter Mode In the Master Transmitter mode, a number of data bytes are transmitted to a Slave
Receiver (see Figure 55). Before Master Transmitter mode can be entered, the TWCR must be initialized as follows:
TWCR Value TWINT 0 TWEA X TWSTA 0 TWSTO 0 TWWC 0 TWEN 1 - 0 TWIE X
TWEN must be set to enable the Two-wire Serial Interface, TWSTA and TWSTO must be cleared. The Master Transmitter mode may now be entered by setting the TWSTA bit. The Twowire Serial Interface logic will then test the Two-wire Serial Bus and generate a START condition as soon as the bus becomes free. When a START condition is transmitted, the Two-wire Serial Interface Interrupt Flag (TWINT) is set by hardware, and the status code in TWSR will be $08. TWDR must then be loaded with the slave address and the Data Direction bit (SLA+W). Clearing the TWINT bit in software will continue the transfer. The TWINT Flag is cleared by writing a logic one to the flag. When the slave address and the direction bit have been transmitted and an acknowledgement bit has been received, TWINT is set again and a number of status codes in TWSR are possible. Possible status codes in Master mode are $18, $20, or $38. The appropriate action to be taken for each of these status codes is detailed in Table 37. The data must be loaded when TWINT is high only. If not, the access will be discarded, and the Write Collision bit - TWWC will be set in the TWCR Register. This scheme is repeated until the last byte is sent and the transfer is ended by generating a STOP condition or a repeated START condition. A STOP condition is generated by setting TWSTO, a repeated START condition is generated by setting TWSTA and TWSTO. After a repeated START condition (state $10) the Two-wire Serial Interface can access the same Slave again, or a new Slave without transmitting a STOP condition. Repeated START enables the Master to switch between Slaves, Master Transmitter mode and Master Receiver mode without loosing control over the bus. Assembly code illustrating operation of the Master Transmitter mode is given at the end of the TWI section.
Master Receiver Mode
In the Master Receiver mode, a number of data bytes are received from a Slave Transmitter (see Figure 56). The transfer is initialized as in the Master Transmitter mode. When the START condition has been transmitted, the TWINT Flag is set by hardware. The software must then load TWDR with the 7-bit slave address and the Data Direction bit (SLA+R). The transfer will then continue when the TWINT Flag is cleared by software. When the slave address and the direction bit have been transmitted and an acknowledgement bit has been received, TWINT is set again and a number of status codes in TWSR are possible. Possible status codes in Master mode are $40, $48, or $38. The appropriate action to be taken for each of these status codes is detailed in Table . Received data can be read from the TWDR Register when the TWINT Flag is set high by hardware. This scheme is repeated until the last byte has been received and a STOP condition is transmitted by writing a logic one to the TWSTO bit in the TWCR Register.
108
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
After a repeated START condition (state $10), the Two-wire Serial Interface may switch to the Master Transmitter mode by loading TWDR with SLA+W or access a new Slave as Master Receiver or Transmitter. Assembly code illustrating operation of the Master Receiver mode is given at the end of the TWI section.
Slave Receiver Mode
In the Slave Receiver mode, a number of data bytes are received from a Master Transmitter (see Figure 57). To initiate the Slave Receiver mode, TWAR and TWCR must be initialized as follows:
TWAR Value TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE Device's Own Slave Address
The upper seven bits are the address to which the Two-wire Serial Interface will respond when addressed by a Master. If the LSB is set, the Two-wire Serial Interface will respond to the general call address ($00), otherwise it will ignore the general call address.
TWCR Value TWINT 0 TWEA 1 TWSTA 0 TWSTO 0 TWWC 0 TWEN 1 - 0 TWIE X
TWEN must be set to enable the Two-wire Serial Interface. The TWEA bit must be set to enable the acknowledgement of the device's own slave address or the general call address. TWSTA and TWSTO must be cleared. When TWAR and TWCR have been initialized, the Two-wire Serial Interface waits until it is addressed by its own slave address (or the general call address if enabled) followed by the Data Direction bit which must be "0" (write) for the Two-wire Serial Interface to operate in the Slave Receiver mode. After its own slave address and the write bit have been received, the Two-wire Serial Interface Interrupt Flag is set and a valid status code can be read from TWSR. The status code is used to determine the appropriate software action. The appropriate action to be taken for each status code is detailed in Table 42. The Slave Receiver mode may also be entered if arbitration is lost while the Two-wire Serial Interface is in the Master mode (see states $68 and $78). If the TWEA bit is reset during a transfer, the Two-wire Serial Interface will return a "Not Acknowledge" ("1") to SDA after the next received data byte. While TWEA is reset, the Two-wire Serial Interface does not respond to its own slave address. However, the Twowire Serial Bus is still monitored and address recognition may resume at any time by setting TWEA. This implies that the TWEA bit may be used to temporarily isolate the Two-wire Serial Interface from the Two-wire Serial Bus. In ADC Noise Reduction mode, Power-down mode, and Power-save mode, the clock system to the Two-wire Serial Interface is turned off. If the Slave Receive mode is enabled, the interface can still acknowledge a general call and its own slave address by using the Two-wire Serial Bus clock as a clock source. The part will then wake up from sleep and the Two-wire Serial Interface will hold the SCL clock will low during the wake up and until the TWINT Flag is cleared. Note that the Two-wire Serial Interface Data Register - TWDR does not reflect the last byte present on the bus when waking up from these sleep modes. Assembly code illustrating operation of the Slave Receiver mode is given at the end of the TWI section.
109
1457G-AVR-09/03
Slave Transmitter Mode
In the Slave Transmitter mode, a number of data bytes are transmitted to a Master Receiver (see Figure 58). The transfer is initialized as in the Slave Receiver mode. When TWAR and TWCR have been initialized, the Two-wire Serial Interface waits until it is addressed by its own slave address (or the general call address if enabled) followed by the Data Direction bit which must be "1" (read) for the Two-wire Serial Interface to operate in the Slave Transmitter mode. After its own slave address and the read bit have been received, the Two-wire Serial Interface Interrupt Flag is set and a valid status code can be read from TWSR. The status code is used to determine the appropriate software action. The appropriate action to be taken for each status code is detailed in Table 43. The Slave Transmitter mode may also be entered if arbitration is lost while the Two-wire Serial Interface is in the Master mode (see state $B0). If the TWEA bit is reset during a transfer, the Two-wire Serial Interface will transmit the last byte of the transfer and enter state $C0 or state $C8. the Two-wire Serial Interface is switched to the not addressed Slave mode, and will ignore the Master if it continues the transfer. Thus the Master Receiver receives all "1" as serial data. While TWEA is reset, the Two-wire Serial Interface does not respond to its own slave address. However, the Two-wire Serial Bus is still monitored and address recognition may resume at any time by setting TWEA. This implies that the TWEA bit may be used to temporarily isolate the Two-wire Serial Interface from the Two-wire Serial Bus. Assembly code illustrating operation of the Slave Receiver mode is given at the end of the TWI section.
Miscellaneous States
There are two status codes that do not correspond to a defined Two-wire Serial Interface state, see Table 37. Status $F8 indicates that no relevant information is available because the Two-wire Serial Interface Interrupt Flag (TWINT) is not set yet. This occurs between other states, and when the Two-wire Serial Interface is not involved in a serial transfer. Status $00 indicates that a bus error has occurred during a Two-wire Serial Bus transfer. A bus error occurs when a START or STOP condition occurs at an illegal position in the format frame. Examples of such illegal positions are during the serial transfer of an address byte, a data byte or an acknowledge bit. When a bus error occurs, TWINT is set. To recover from a bus error, the TWSTO Flag must set and TWINT must be cleared by writing a logic one to it. This causes the Two-wire Serial Interface to enter the not addressed Slave mode and to clear the TWSTO Flag (no other bits in TWCR are affected). The SDA and SCL lines are released and no STOP condition is transmitted.
110
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Table 37. Miscellaneous States
Application Software Response Status Code (TWSR) $08 $10 Status of the Two-wire Serial Bus and Two-wire Serial Interface Hardware A START condition has been transmitted A repeated START condition has been transmitted To TWCR To/from TWDR Load SLA+W Load SLA+W or Load SLA+R $18 SLA+W has been transmitted; ACK has been received Load data byte or No TWDR action or No TWDR action or No TWDR action $20 SLA+W has been transmitted; NOT ACK has been received Load data byte or No TWDR action or No TWDR action or No TWDR action $28 Data byte has been transmitted; ACK has been received Load data byte or No TWDR action or No TWDR action or No TWDR action $30 Data byte has been transmitted; NOT ACK has been received Load data byte or No TWDR action or No TWDR action or No TWDR action $38 Arbitration lost in SLA+W or data bytes No TWDR action or No TWDR action STA X X X 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 STO 0 0 0 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 TWINT 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 TWEA X X X X X X X X X X X X X X X X X X X X X Next Action Taken by Two-wire Serial Interface Hardware SLA+W will be transmitted; ACK or NOT ACK will be received SLA+W will be transmitted; ACK or NOT ACK will be received SLA+R will be transmitted; Logic will switch to Master Receiver mode Data byte will be transmitted and ACK or NOT ACK will be received Repeated START will be transmitted STOP condition will be transmitted and TWSTO Flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO Flag will be reset Data byte will be transmitted and ACK or NOT ACK will be received Repeated START will be transmitted STOP condition will be transmitted and TWSTO Flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO Flag will be reset Data byte will be transmitted and ACK or NOT ACK will be received Repeated START will be transmitted STOP condition will be transmitted and TWSTO Flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO Flag will be reset Data byte will be transmitted and ACK or NOT ACK will be received Repeated START will be transmitted STOP condition will be transmitted and TWSTO Flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO Flag will be reset Two-wire Serial Bus will be released and not addressed Slave mode entered A START condition will be transmitted when the bus becomes free
111
1457G-AVR-09/03
Figure 55. Formats and States in the Master Transmitter Mode
MT
Successfull Transmission to a Slave Receiver
S
SLA
W
A
DATA
A
P
$08
Next Transfer Started with a Repeated Start Condition
$18
$28
S
SLA
W
$10
Not Acknowledge Received after the Slave Address
A
P
R
$20
MR
Not Acknowledge Received after a Data Byte
A
P
$30
Arbitration Lost in Slave Address or Data Byte
A or A
Other Master Continues
A or A
Other Master Continues
$38
Arbitration Lost and Addressed as Slave
$38
Other Master Continues
A
$68
$78
$B0
To Corresponding States in Slave Mode
From Master to Slave
DATA
A
Any Number of Data Bytes and their Associated Acknowledge Bits This Number (Contained in TWSR) Corresponds to a Defined State of the Two-wire Serial Bus
From Slave to Master
n
Assembly Code Example - Master Transmitter Mode
;The Slave being addressed has address 0x64. The code examples also assumes some sort of error handling routine named ERROR. ;Part specific include file and TWI include file must be included.
; ldi out r16, (1<wait1: in
r16,TWCR
; Wait for TWINT Flag set. This indicates that ; the START condition has been transmitted
sbrs r16,TWINT rjmp wait1
in cpi
r16, TWSR r16, START
; Check value of TWI Status Register. ; If status different from START go to ERROR
brne ERROR
112
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
ldi out ldi out r16, 0xc8 TWDR, r16 r16, (1<wait2: in
r16, TWCR
sbrs r16, TWINT rjmp wait2 in cpi r16, TWSR r16, MT_SLA_ACK
brne ERROR ldi out ldi out r16, 0x33 TWDR, r16 r16, (1<wait3: in
r16, TWCR
sbrs r16, TWINT rjmp wait3 in cpi r16, TWSR
r16, MT_DATA_ACK ; different from MT_DATA_ACK, go to ERROR
brne ERROR ldi out ldi out r16, 0x44 TWDR, r16 r16, (1<;
wait4: in
r16, TWCR
; Wait for TWINT Flag set. This indicates that ; data has been transmitted, and ACK/NACK has ; been received
sbrs r16, TWINT rjmp wait4
in cpi
r16, TWSR
; Check value of TWI Status Register. If status
r16, MT_DATA_ACK ; different from MT_DATA_ACK, go to ERROR
brne ERROR
ldi out
r16, (1<113
1457G-AVR-09/03
Table 38. Miscellaneous States
Application Software Response Status Code (TWSR) $08 $10 Status of the Two-wire Serial Bus and Two-wire Serial Interface hardware A START condition has been transmitted A repeated START condition has been transmitted To TWCR To/from TWDR Load SLA+R Load SLA+R or Load SLA+W $38 Arbitration lost in SLA+R or NOT ACK bit No TWDR action or No TWDR action $40 SLA+R has been transmitted; ACK has been received No TWDR action or No TWDR action $48 SLA+R has been transmitted; NOT ACK has been received No TWDR action or No TWDR action or No TWDR action $50 Data byte has been received; ACK has been returned Data byte has been received; NOT ACK has been returned Read data byte or Read data byte $58 Read data byte or Read data byte or Read data byte STA X X X 0 1 0 0 1 0 1 0 0 1 0 1 STO 0 0 0 0 0 0 0 0 1 1 0 0 0 1 1 TWINT 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 TWEA X X X X X 0 1 X X X 0 1 X X X Next Action Taken by Two-wire Serial Interface Hardware SLA+R will be transmitted ACK or NOT ACK will be received SLA+R will be transmitted ACK or NOT ACK will be received SLA+W will be transmitted Logic will switch to Master Transmitter mode\ Two-wire Serial Bus will be released and not addressed Slave mode will be entered A START condition will be transmitted when the bus becomes free Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Repeated START will be transmitted STOP condition will be transmitted and TWSTO Flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO Flag will be reset Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Repeated START will be transmitted STOP condition will be transmitted and TWSTO Flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO Flag will be reset
114
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Figure 56. Formats and States in the Master Receiver Mode
MR
Successfull Reception from a Slave Receiver
S
SLA
R
A
DATA
A
DATA
A
P
$08
Next Transfer Started with a Repeated Start Condition
$40
$50
$58
S
SLA
R
$10
Not Acknowledge Received after the Slave Address
A
P
W
$48
MT
Arbitration Lost in Slave Address or Data Byte
A or A
Other Master Continues
A
Other Master Continues
$38
Arbitration Lost and Addressed as Slave
$38
Other Master Continues
A
$68
$78
$B0
To Corresponding States in Slave Mode
From Master to Slave
DATA
A
Any Number of Data Bytes and their Associated Acknowledge Bits This Number (Contained in TWSR) Corresponds to a Defined State of the Two-wire Serial Bus
From Slave to Master
n
Assembly Code Example - Master Receiver Mode
;Part specific include file and TWI include file must be included. ;
ldi
r16, (1<wait5:in
r16,TWCR
sbrs r16, TWINT rjmp wait5 in cpi r16, TWSR r16, START
; Check value of TWI Status Register. If status ; different from START, go to ERROR
brne ERROR ldi out ldi out r16, 0xc9 TWDR, r16 r16, (1<wait6:in
r16,TWCR
; Wait for TWINT Flag set. This indicates that ; SLA+R has been transmitted, and ACK/NACK has ; been received
sbrs r16, TWINT rjmp wait6
115
1457G-AVR-09/03
in cpi
r16, TWSR r16, MR_SLA_ACK
; Check value of TWI Status Register. If status ; different from MR_SLA_ACK, go to ERROR
brne ERROR
ldi out
r16, (1<wait7:in
r16,TWCR
sbrs r16, TWINT rjmp wait7 in cpi r16, TWSR r16, MR_DATA_ACK
; Check value of TWI Status Register. If status ; different from MR_DATA_ACK, go to ERROR
brne ERROR in nop ldi out r16, TWDR ; Input received data from TWDR. ; r16, (1<;
;receive next to last data byte. wait8:in r16,TWCR ; Wait for TWINT Flag set. This indicates that ; data has been received and ACK returned sbrs r16, TWINT rjmp wait8 in cpi r16, TWSR r16, MR_DATA_ACK ; Check value of TWI Status Register. If status ; different from MR_DATA_ACK, go to ERROR
brne ERROR in nop ldi out r16, TWDR ; Input received data from TWDR. ; r16, (1<wait9:in
r16,TWCR
; Wait for TWINT Flag set. This indicates that ; data has been received and NACK returned
sbrs r16, TWINT rjmp wait9 in cpi r16, TWSR r16, MR_DATA_NACK
; Check value of TWI Status Register. If status ; different from MR_DATA_NACK, go to ERROR
brne ERROR
116
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
in nop ldi out r16, TWDR ; Input received data from TWDR. ; r16, (1<Table 39. Miscellaneous States
Application Software Response Status Code (TWSR) $60 Status of the Two-wire Serial Bus and Two-wire Serial Interface Hardware Own SLA+W has been received; ACK has been returned Arbitration lost in SLA+R/W as Master; own SLA+W has been received; ACK has been returned General call address has been received; ACK has been returned Arbitration lost in SLA+R/W as Master; General call address has been received; ACK has been returned Previously addressed with own SLA+W; data has been received; ACK has been returned Previously addressed with own SLA+W; data has been received; NOT ACK has been returned To TWCR To/from TWDR No TWDR action or No TWDR action $68 No TWDR action or No TWDR action No TWDR action or No TWDR action $78 No TWDR action or No TWDR action Read data byte or Read data byte Read data byte or Read data byte or STA X X X X X X X X X X 0 0 STO 0 0 0 0 0 0 0 0 0 0 0 0 TWINT 1 1 1 1 1 1 1 1 1 1 1 1 TWEA 0 1 0 1 0 1 0 1 0 1 0 1 Next Action Taken by Two-wire Serial Interface Hardware Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free
$70
$80
$88
Read data byte or
1
0
1
0
Read data byte
1
0
1
1
$90
Previously addressed with general call; data has been received; ACK has been returned Previously addressed with general call; data has been received; NOT ACK has been returned
Read data byte or Read data byte Read data byte or Read data byte or
X X 0 0
0 0 0 0
1 1 1 1
0 1 0 1
$98
Read data byte or
1
0
1
0
Read data byte
1
0
1
1
$A0
A STOP condition or repeated START condition has been received while still addressed as Slave
Read data byte or Read data byte or
0 0
0 0
1 1
0 1
Read data byte or
1
0
1
0
Read data byte
1
0
1
1
117
1457G-AVR-09/03
Figure 57. Formats and States in the Slave Receiver Mode
Reception of the Own Slave Address and One or more Data Bytes. All are Acknowledged
S
SLA
W
A
DATA
A
DATA
A
P or S
$60
Last Data Byte Received is not Acknowledged
$80
$80
$A0
A
P or S
$88
Arbitration Lost as Master and Addressed as Slave
A
$68
Reception of the General Call Address and One or more Data Bytes
General Call
A
DATA
A
DATA
A
P or S
$70
Last Data Byte received is not Acknowledged
$90
$90
$A0
A
P or S
$98
Arbitration Lost as Master and Addressed as Slave by General Call
A
$78
From Master to Slave
DATA
A
Any Number of Data Bytes and their Associated Acknowledge Bits This Number (Contained in TWSR) Corresponds to a Defined State of the Two-wire Serial Bus
From Slave to Master
n
Assembly Code Example - Slave Receiver Mode
;Part specific include file and TWI include file must be included. ;
ldi out
r16, (1<;
wait10:in
r16,TWCR
; Wait for TWINT Flag set. This indicates that ; START followed by SLA+W has been received
sbrs r16, TWINT rjmp wait10
in cpi
r16, TWSR r16, SR_SLA_ACK
; Check value of TWI Status Register. If status ; different from SR_SLA_ACK, go to ERROR
brne ERROR
ldi out
r16, (1<118
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
; ACK should be returned after receiving first ; data byte wait12:in r16,TWCR ; Wait for TWINT Flag set. This indicates that ; data has been received and ACK returned
sbrs r16, TWINT rjmp wait12 in cpi r16, TWSR r16, SR_DATA_ACK
; Check value of TWI Status Register. If status ; different from SR_DATA_ACK, go to ERROR
brne ERROR in nop ldi out r16, TWDR ; Input received data from TWDR. ; r16, (1<wait13:in
r16,TWCR
sbrs r16, TWINT rjmp wait13 in cpi r16, TWSR r16, SR_DATA_NACK
; Check value of TWI Status Register. If status ; different from SR_DATA_NACK, go to ERROR
brne ERROR in nop ldi out r16, TWDR ; Input received data from TWDR. ; r16, (1<;
119
1457G-AVR-09/03
Table 40. Miscellaneous States
Application Software Response Status Code (TWSR) $A8 Status of the Two-wire Serial Bus and Two-wire Serial Interface Hardware Own SLA+R has been received; ACK has been returned To TWCR To/from TWDR Load data byte or Load data byte $B0 Arbitration lost in SLA+R/W as Master; own SLA+R has been received; ACK has been returned Data byte in TWDR has been transmitted; ACK has been received Data byte in TWDR has been transmitted; NOT ACK has been received Load data byte or Load data byte Load data byte or Load data byte No TWDR action or No TWDR action or STA X X X X X X 0 0 STO 0 0 0 0 0 0 0 0 TWINT 1 1 1 1 1 1 1 1 TWEA 0 1 0 1 0 1 0 1 Next Action Taken by Two-wire Serial Interface Hardware Last data byte will be transmitted and NOT ACK should be received Data byte will be transmitted and ACK should be received Last data byte will be transmitted and NOT ACK should be received Data byte will be transmitted and ACK should be received Last data byte will be transmitted and NOT ACK should be received Data byte will be transmitted and ACK should be received Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free
$B8
$C0
No TWDR action or
1
0
1
0
No TWDR action
1
0
1
1
$C8
Last data byte in TWDR has been transmitted (TWEA = "0"); ACK has been received
No TWDR action or No TWDR action or
0 0
0 0
1 1
0 1
No TWDR action or
1
0
1
0
No TWDR action
1
0
1
1
120
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Figure 58. Formats and States in the Slave Transmitter Mode
Reception of the Own Slave Address and One or More Data Bytes
S
SLA
R
A
DATA
A
DATA
A
P or S
$A8
Arbitration Lost as Master and Addressed as Slave
$B8
$C0
A
$B0
Last Data Byte Transmitted. Switched to not Addressed Slave (TWEA = '0')
A
All 1's
P or S
$C8
From Master to Slave
DATA
A
Any Number of Data Bytes and their Associated Acknowledge Bits This Number (Contained in TWSR) Corresponds to a Defined State of the Two-wire Serial Bus
From Slave to Master
n
Assembly Code Example - Slave Transmitter Mode
; Part specific include file and TWI include file must be included. ;
ldi out
r16, (1<; wait14:in r16,TWCR ; Wait for TWINT Flag set. This indicates that ; SLA+R has been received, and ACK/NACK has ; been returned
sbrs r16, TWINT rjmp wait14
in cpi
r16, TWSR r16, ST_SLA_ACK
; Check value of TWI Status Register. If status ; different from ST_SLA_ACK, go to ERROR
brne ERROR
ldi out ldi out
r16, 0x33 TWDR, r16
; Load data(here, data=0x33)into TWDR Register
r16, (1<; wait15:in r16,TWCR sbrs r16, TWINT rjmp wait15 in cpi r16, TWSR r16, ST_DATA_ACK
brne ERROR
121
1457G-AVR-09/03
ldi out ldi out
r16, 0x44 TWDR, r16
; Load data(here, data=0x44)into TWDR Register
r16, (1<wait16:in
r16,TWCR
sbrs r16, TWINT rjmp wait16
in cpi ldi out ldi out
r16, TWSR r16, ST_DATA_ACK r16, 0x55 TWDR, r16
; Check value of TWI Status Register. If status ; different from ST_DATA_ACK, go to ERROR ; Load data(here, data=0x55)into TWDR Register
brne ERROR
r16, (1<wait17:in
r16,TWCR
; Wait for TWINT Flag set. This indicates that ; data has been transmitted, and ACK/NACK has ; been received
sbrs r16, TWINT rjmp wait17
in cpi
r16, TWSR r16, ST_LAST_DATA
; Check value of TWI Status Register. If status ; different from ST_LAST_DATA, go to ERROR
brne ERROR
ldi out
r16, (1<Table 41. Miscellaneous States
Application Software Response Status Code (TWSR) $F8 $00 Status of the Two-wire Serial Bus and Two-wire Serial Interface Hardware No relevant state information available; TWINT = "0" Bus error due to an illegal START or STOP condition To TWCR To/from TWDR No TWDR action No TWDR action 0 STA STO TWINT TWEA Next Action Taken by Two-wire Serial Interface Hardware Wait or proceed current transfer X Only the internal hardware is affected, no STOP condition is sent on the bus. In all cases, the bus is released and TWSTO is cleared.
No TWCR action 1 1
TWI Include File
;***** General Master status codes ***** .equ .equ START REP_START =$08 =$10 ;START has been transmitted ;Repeated START has been transmitted
;***** Master Transmitter status codes ***** .equ .equ .equ MT_SLA_ACK MT_SLA_NACK MT_DATA_ACK =$18 =$20 =$28 ;SLA+W has been transmitted and ACK received ;SLA+W has been transmitted and NACK received ;Data byte has been transmitted and ACK ;received
122
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
.equ .equ MT_DATA_NACK MT_ARB_LOST =$30 =$38 ;Data byte has been transmitted and NACK ;received ;Arbitration lost in SLA+W or data bytes
;***** Master Receiver status codes ***** .equ .equ .equ .equ .equ MR_ARB_LOST MR_SLA_ACK MR_SLA_NACK MR_DATA_ACK MR_DATA_NACK =$38 =$40 =$48 =$50 =$58 ;Arbitration lost in SLA+R or NACK bit ;SLA+R has been transmitted and ACK received ;SLA+R has been transmitted and NACK received ;Data byte has been received and ACK returned ;Data byte has been received and NACK ;transmitted
;***** Slave Transmitter status codes ***** .equ .equ .equ .equ .equ ST_SLA_ACK =$A8 ;Own SLA+R has been received and ACK returned ST_ARB_LOST_SLA_ACK=$B0 ;Arbitration lost in SLA+R/W as Master. Own ;SLA+W has been received and ACK returned ST_DATA_ACK ST_DATA_NACK ST_LAST_DATA =$B8 =$C0 =$C8 ;Data byte has been transmitted and ACK ;received ;Data byte has been transmitted and NACK ;received ;Last byte in I2DR has been transmitted ;(TWEA = "0"), ACK has been received
;***** Slave Receiver status codes ***** .equ .equ .equ .equ SR_SLA_ACK =$60 ;SLA+R has been received and ACK returned SR_ARB_LOST_SLA_ACK=$68;Arbitration lost in SLA+R/W as Master. Own ;SLA+R has been received and ACK returned SR_GCALL_ACK =$70 ;General call has been received and ACK ;returned
SR_ARB_LOST_GCALL_ACK=$78;Arbitration lost in SLA+R/W as Master. ;General Call has been received and ACK ;returned SR_DATA_ACK SR_DATA_NACK =$80 =$88 ;Previously addressed with own SLA+W. Data byte ;has been received and ACK returned ;Previously addressed with own SLA+W. Data byte ;has been received and NACK returned
.equ .equ .equ .equ .equ
SR_GCALL_DATA_ACK=$90 ;Previously addressed with General Call.Data ;byte has been received and ACK returned SR_GCALL_DATA_NACK=$98 ;Previously addressed with General Call. Data ;byte has been received and NACK returned SR_STOP =$A0 ;A STOP condition or repeated START condition ;has been received while still addressed as a ;Slave
;***** Miscellaneous States ***** .equ .equ NO_INFO BUS_ERROR =$F8 =$00 ;No relevant state information; TWINT = ;Bus error due to illegal START or STOP ;condition
"0"
123
1457G-AVR-09/03
The Analog Comparator
The Analog Comparator compares the input values on the positive pin PB2 (AIN0) and negative pin PB3 (AIN1). When the voltage on the positive pin PB2 (AIN0) is higher than the voltage on the negative pin PB3 (AIN1), the Analog Comparator Output, ACO, is set (one). The comparator's output can be set to trigger the Timer/Counter1 Input Capture function. In addition, the comparator can trigger a separate interrupt, exclusive to the Analog Comparator. The user can select Interrupt triggering on comparator output rise, fall or toggle. A block diagram of the comparator and its surrounding logic is shown in Figure 59. Figure 59. Analog Comparator Block Diagram
BANDGAP REFERENCE ACBG
ACME ADEN ADC MULTIPLEXER 1) OUTPUT
Note:
See Figure 60 on page 128.
124
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
The Analog Comparator Control and Status Register - ACSR
Bit $08 ($28) Read/Write Initial Value
7 ACD R/W 0
6 ACBG R/W 0
5 ACO R N/A
4 ACI R/W 0
3 ACIE R/W 0
2 ACIC R/W 0
1 ACIS1 R/W 0
0 ACIS0 R/W 0 ACSR
* Bit 7 - ACD: Analog Comparator Disable When this bit is set(one), the power to the Analog Comparator is switched off. This bit can be set at any time to turn off the Analog Comparator. This will reduce power consumption in active and idle mode. When changing the ACD bit, the Analog Comparator Interrupt must be disabled by clearing the ACIE bit in ACSR. Otherwise an interrupt can occur when the bit is changed. * Bit 6 - ACBG: Analog Comparator Bandgap Select When this bit is set, a fixed bandgap voltage of nominally 1.22 0.10V replaces the positive input to the Analog Comparator. When this bit is cleared, AIN0 is applied to the positive input of the Analog Comparator. See "Internal Voltage Reference" on page 31. * Bit 5 - ACO: Analog Comparator Output ACO is directly connected to the comparator output. * Bit 4 - ACI: Analog Comparator Interrupt Flag This bit is set (one) when a comparator output event triggers the interrupt mode defined by ACIS1 and ACIS0. The Analog Comparator Interrupt routine is executed if the ACIE bit is set (one) and the I-bit in SREG is set (one). ACI is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, ACI is cleared by writing a logic one to the flag. * Bit 3 - ACIE: Analog Comparator Interrupt Enable When the ACIE bit is set (one) and the I-bit in the Status Register is set (one), the analog comparator interrupt is activated. When cleared (zero), the interrupt is disabled. * Bit 2 - ACIC: Analog Comparator Input Capture Enable When set (one), this bit enables the Input Capture function in Timer/Counter1 to be triggered by the Analog Comparator. The comparator output is in this case directly connected to the Input Capture Front-end Logic, making the comparator utilize the noise canceler and edge select features of the Timer/Counter1 Input Capture Interrupt. When cleared (zero), no connection between the Analog Comparator and the Input Capture function is given. To make the comparator trigger the Timer/Counter1 Input Capture Interrupt, the TICIE1 bit in the Timer Interrupt Mask Register (TIMSK) must be set (one).
125
1457G-AVR-09/03
* Bits 1, 0 - ACIS1, ACIS0: Analog Comparator Interrupt Mode Select These bits determine which comparator events that trigger the Analog Comparator interrupt. The different settings are shown in Table 42. Table 42. ACIS1/ACIS0 Settings
ACIS1 0 0 1 1 ACIS0 0 1 0 1 Interrupt Mode Comparator Interrupt on Output Toggle Reserved Comparator Interrupt on Falling Output Edge Comparator Interrupt on Rising Output Edge
When changing the ACIS1/ACIS0 bits, The Analog Comparator Interrupt must be disabled by clearing its Interrupt Enable bit in the ACSR Register. Otherwise an interrupt can occur when the bits are changed.
Analog Comparator Multiplexed Input
It is possible to select any of the ADC7..0 pins to replace the negative input to the Analog Comparator. The ADC multiplexer is used to select this input, and consequently, the ADC must be switched off to utilize this feature. If the Analog Comparator Multiplexer Enable bit (ACME in SFIOR) is set and the ADC is switched off (ADEN in ADCSRA is zero), MUX2..0 in ADMUX select the input pin to replace the negative input to the Analog Comparator, as shown in Table 43. If ACME is cleared (zero) or ADEN is set (one), PB3 (AIN1) is applied to the negative input to the Analog Comparator. Table 43. Analog Comparator Multiplexed Input
ACME 0 1 1 1 1 1 1 1 1 1 ADEN x 1 0 0 0 0 0 0 0 0 MUX2..0 xxx xxx 000 001 010 011 100 101 110 111 Analog Comparator Negative Input AIN1 AIN1 ADC0 ADC1 ADC2 ADC3 ADC4 ADC5 ADC6 ADC7
126
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Analog to Digital Converter
Features
* * * * * * * * * * * * *
10-bit Resolution 0.5 LSB Integral Non-linearity 2 LSB Absolute Accuracy 65 - 260 s Conversion Time Up to 15 kSPS at Maximum Resolution Up to 76 kSPS at 8-bit Resolution Eight Multiplexed Single Ended Input Channels Optional Left Adjustment for ADC Result Readout 0 - VCC ADC Input Voltage Range Selectable 2.56V ADC Reference Voltage Free Run or Single Conversion Mode Interrupt on ADC Conversion Complete Sleep Mode Noise Canceler
The ATmega323 features a 10-bit successive approximation ADC. The ADC is connected to an 8-channel Analog Multiplexer which allows each pin of Port A to be used as input for the ADC. The ADC contains a Sample and Hold Amplifier which ensures that the input voltage to the ADC is held at a constant level during conversion. A block diagram of the ADC is shown in Figure 60. The ADC has two separate analog supply voltage pins, AVCC and AGND. AGND must be connected to GND, and the voltage on AVCC must not differ more than 0.3V from VCC. See the paragraph ADC Noise Canceling Techniques on how to connect these pins. Internal reference voltages of nominally 2.56V or AVCC are provided On-chip. The 2.56V reference may be externally decoupled at the AREF pin by a capacitor for better noise performance. See "Internal Voltage Reference" on page 31 for a description of the internal voltage reference.
127
1457G-AVR-09/03
Figure 60. Analog to Digital Converter Block Schematic
ADC CONVERSION COMPLETE IRQ
8-BIT DATA BUS
ADIF ADIE
15 ADC DATA REGISTER (ADCH/ADCL)
ADPS0
0
ADC MULTIPLEXER SELECT (ADMUX)
MUX4 MUX3 MUX2 MUX1 ADLAR REFS1 REFS0 MUX0
ADC CTRL. & STATUS REGISTER (ADCSR)
ADPS2 ADPS1 ADEN
ADSC
ADFR
ADIF
PRESCALER MUX DECODER
CHANNEL SELECTION
CONVERSION LOGIC
AVCC
INTERNAL 2.56 V REFERENCE AREF
10-BIT DAC
SAMPLE & HOLD COMPARATOR +
AGND
1.22 V BANDGAP REFERENCE
ADC7 ADC6 ADC5 ADC4 ADC3 ADC2 ADC1 ADC0
INPUT MUX
ADC MULTIPLEXER OUTPUT
Operation
The ADC converts an analog input voltage to a 10-bit digital value through successive approximation. The minimum value represents AGND and the maximum value represents the voltage on the AREF pin minus 1 LSB. Optionally, AVCC or an internal 2.56V reference voltage may be connected to the AREF pin by writing to the REFSn bits in the ADMUX Register. The internal voltage reference may thus be decoupled by an external capacitor at the AREF pin to improve noise immunity. The analog input channel is selected by writing to the MUX bits in ADMUX. Any of the eight ADC input pins ADC7..0, as well as AGND and a fixed bandgap voltage reference of nominally 1.22 V (VBG), can be selected as single ended inputs to the ADC. The ADC can operate in two modes - Single Conversion and Free Running mode. In Single Conversion mode, each conversion will have to be initiated by the user. In Free Running mode, the ADC is constantly sampling and updating the ADC Data Register. The ADFR bit in ADCSR selects between the two available modes.
128
ATmega323(L)
1457G-AVR-09/03
ADC[9:0]
ATmega323(L)
The ADC is enabled by setting the ADC Enable bit, ADEN in ADCSR. Voltage reference and input channel selections will not go into effect until ADEN is set. The ADC does not consume power when ADEN is cleared, so it is recommended to switch off the ADC before entering power saving sleep modes. A conversion is started by writing a logical one to the ADC Start Conversion bit, ADSC. This bit stays high as long as the conversion is in progress and will be set to zero by hardware when the conversion is completed. If a different data channel is selected while a conversion is in progress, the ADC will finish the current conversion before performing the channel change. The ADC generates a 10-bit result, which are presented in the ADC Data Registers, ADCH and ADCL. By default, the result is presented right adjusted, but can optionally be presented left adjusted by setting the ADLAR bit in ADMUX. If the result is left adjusted and no more than 8-bit precision is required, it is sufficient to read ADCH. Otherwise, ADCL must be read first, then ADCH, to ensure that the content of the Data Registers belongs to the same conversion. Once ADCL is read, ADC access to Data Registers is blocked. This means that if ADCL has been read, and a conversion completes before ADCH is read, neither register is updated and the result from the conversion is lost. When ADCH is read, ADC access to the ADCH and ADCL Registers is re-enabled. The ADC has its own interrupt which can be triggered when a conversion completes. When ADC access to the Data Registers is prohibited between reading of ADCH and ADCL, the interrupt will trigger even if the result is lost.
Prescaling and Conversion Timing
Figure 61. ADC Prescaler
ADEN CK Reset 7-BIT ADC PRESCALER
ADPS0 ADPS1 ADPS2
ADC CLOCK SOURCE
The successive approximation circuitry requires an input clock frequency between 50 kHz and 200 kHz to achieve maximum resolution. If a lower resolution than 10 bits is required, the input clock frequency to the ADC can be higher than 200 kHz to achieve a higher sampling rate. See "ADC Characteristics - Preliminary Data" on page 136 for more details. The ADC module contains a prescaler, which divides the system clock to an acceptable ADC clock frequency. The ADPS bits in ADCSR are used to generate a proper ADC clock input frequency from any XTAL frequency above 100 kHz. The prescaler starts counting from the moment the ADC is switched on by setting the ADEN bit in ADCSR. The prescaler
CK/128
CK/16
CK/32
CK/64
CK/2
CK/4
CK/8
129
1457G-AVR-09/03
keeps running for as long as the ADEN bit is set, and is continuously reset when ADEN is low. When initiating a conversion by setting the ADSC bit in ADCSR, the conversion starts at the following rising edge of the ADC clock cycle. A normal conversion takes 13 ADC clock cycles. In certain situations, the ADC needs more clock cycles to initialization and minimize offset errors. Extended conversions take 25 ADC clock cycles and occur as the first conversion after the ADC is switched on (ADEN in ADCSR is set). Additionally, when changing voltage reference, the user may improve accuracy by disregarding the first conversion result after the reference or MUX setting was changed. The actual sample-and-hold takes place 1.5 ADC clock cycles after the start of a normal conversion and 13.5 ADC clock cycles after the start of an extended conversion. When a conversion is complete, the result is written to the ADC Data Registers, and ADIF is set. In Single Conversion mode, ADSC is cleared simultaneously. The software may then set ADSC again, and a new conversion will be initiated on the first rising ADC clock edge. In Free Running mode, a new conversion will be started immediately after the conversion completes, while ADSC remains high. Using Free Running mode and an ADC clock frequency of 200 kHz gives the lowest conversion time with a maximum resolution, 65 s, equivalent to 15 kSPS. For a summary of conversion times, see Table 43. Figure 62. ADC Timing Diagram, Extended Conversion (Single Conversion Mode)
Extended Conversion Next Conversion
Cycle Number
1
2
12
13
14
15
16
17
18
19
20
21
22
23
24
25
1
2
3
ADC Clock ADEN ADSC ADIF ADCH ADCL Sign and MSB of Result LSB of Result
MUX and REFS Update
Sample & Hold
Conversion Complete
MUX and REFS Update
Figure 63. ADC Timing Diagram, Single Conversion
One Conversion Next Conversion
Cycle Number ADC Clock ADSC ADIF ADCH ADCL
1
2
3
4
5
6
7
8
9
10
11
12
13
1
2
3
Sign and MSB of Result LSB of Result Sample & Hold MUX and REFS Update Conversion Complete
MUX and REFS Update
130
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Figure 64. ADC Timing Diagram, Free Run Conversion
One Conversion 11 12 13 Next Conversion 1 2 3 4
Cycle Number ADC Clock ADSC ADIF ADCH ADCL
Sign and MSB of Result LSB of Result
Conversion Complete
Sample & Hold MUX and REFS Update
Table 44. ADC Conversion Time
Condition Extended Conversion Normal Conversions Sample & Hold (Cycles from Start of Conversion) 13.5 1.5 Conversion Time (Cycles) 25 13 Conversion Time (s) 125 - 500 65 - 260
ADC Noise Canceler Function
The ADC features a noise canceler that enables conversion during ADC Noise Reduction mode (see "Sleep Modes" on page 39) to reduce noise induced from the CPU core and other I/O peripherals. If other I/O peripherals must be active during conversion, this mode works equivalently for Idle mode. To make use of this feature, the following procedure should be used: 1. Make sure that the ADC is enabled and is not busy converting. Single Conversion mode must be selected and the ADC conversion complete interrupt must be enabled. ADEN = 1 ADSC = 0 ADFR = 0 ADIE = 1 2. Enter ADC Noise Reduction mode (or Idle mode). The ADC will start a conversion once the CPU has been halted. 3. If no other interrupts occur before the ADC conversion completes, the ADC interrupt will wake up the CPU and execute the ADC Conversion Complete interrupt routine.
131
1457G-AVR-09/03
The ADC Multiplexer Selection Register - ADMUX
Bit $07 ($27) Read/Write Initial Value
7 REFS1 R/W 0
6 REFS0 R/W 0
5 ADLAR R/W 0
4 MUX4 R/W 0
3 MUX3 R/W 0
2 MUX2 R/W 0
1 MUX1 R/W 0
0 MUX0 R/W 0 ADMUX
* Bit 7, 6 - REFS1..0: Reference Selection Bits These bits select the voltage reference for the ADC, as shown in Table 22. If these bits are changed during a conversion, the change will not go in effect until this conversion is complete (ADIF in ADCSR is set). The user should disregard the first conversion result after changing these bits to obtain maximum accuracy. The internal voltage reference options may not be used if an external reference voltage is being applied to the AREF pin. Table 45. Voltage Reference Selections for ADC
REFS1 0 0 1 1 REFS0 0 1 0 1 Voltage Reference Selection AREF, Internal Vref turned off AVCC with external capacitor at AREF pin Reserved Internal 2.56V Voltage Reference with external capacitor at AREF pin
*
Bit 5 - ADLAR: ADC Left Adjust Result
The ADLAR bit affects the presentation of the ADC conversion result in the ADC Data Register. If ADLAR is cleared, the result is right adjusted. If ADLAR is set, the result is left adjusted. Changing the ADLAR bit will affect the ADC Data Register immediately, regardless of any ongoing conversions. For a complete description of this bit, see "The ADC Data Register - ADCL and ADCH" on page 134. * Bits 4..0 - MUX4..MUX0: Analog Channel Selection Bits The value of these bits selects which combination of analog inputs are connected to the ADC. See Table 46 for details. If these bits are changed during a conversion, the change will not go in effect until this conversion is complete (ADIF in ADCSR is set). Table 46. Input Channel Selections
MUX4..0 00000 00001 00010 00011 00100 00101 00110 00111 Single-ended Input ADC0 ADC1 ADC2 ADC3 ADC4 ADC5 ADC6 ADC7
132
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Table 46. Input Channel Selections (Continued)
MUX4..0 01000..11101 11110 11111 Single-ended Input Reserved 1.22V (VBG) 0V (AGND)
The ADC Control and Status Register - ADCSR
Bit $06 ($26) Read/Write Initial Value
7 ADEN R/W 0
6 ADSC R/W 0
5 ADFR R/W 0
4 ADIF R/W 0
3 ADIE R/W 0
2 ADPS2 R/W 0
1 ADPS1 R/W 0
0 ADPS0 R/W 0 ADCSR
* Bit 7 - ADEN: ADC Enable Writing a logical "1" to this bit enables the ADC. By clearing this bit to zero, the ADC is turned off. Turning the ADC off while a conversion is in progress, will terminate this conversion. * Bit 6 - ADSC: ADC Start Conversion In Single Conversion mode, a logical "1" must be written to this bit to start each conversion. In Free Running mode, a logical "1" must be written to this bit to start the first conversion. The first time ADSC has been written after the ADC has been enabled, or if ADSC is written at the same time as the ADC is enabled, an extended conversion will precede the initiated conversion. This extended conversion performs initialization of the ADC. ADSC will read as one as long as a conversion is in progress. When the conversion is complete, it returns to zero. When a extended conversion precedes a real conversion, ADSC will stay high until the real conversion completes. Writing a 0 to this bit has no effect. * Bit 5 - ADFR: ADC Free Running Select When this bit is set (one) the ADC operates in Free Running mode. In this mode, the ADC samples and updates the Data Registers continuously. Clearing this bit (zero) will terminate Free Running mode. * Bit 4 - ADIF: ADC Interrupt Flag This bit is set (one) when an ADC conversion completes and the Data Registers are updated. The ADC Conversion Complete Interrupt is executed if the ADIE bit and the Ibit in SREG are set (one). ADIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, ADIF is cleared by writing a logical one to the flag. Beware that if doing a Read-Modify-Write on ADCSR, a pending interrupt can be disabled. This also applies if the SBI and CBI instructions are used. * Bit 3 - ADIE: ADC Interrupt Enable When this bit is set (one) and the I-bit in SREG is set (one), the ADC Conversion Complete Interrupt is activated.
133
1457G-AVR-09/03
* Bits 2..0 - ADPS2..0: ADC Prescaler Select Bits These bits determine the division factor between the XTAL frequency and the input clock to the ADC. Table 47. ADC Prescaler Selections
ADPS2 0 0 0 0 1 1 1 1 ADPS1 0 0 1 1 0 0 1 1 ADPS0 0 1 0 1 0 1 0 1 Division Factor 2 2 4 8 16 32 64 128
The ADC Data Register - ADCL and ADCH ADLAR = 0
Bit $05 ($25) $04 ($24) 15 SIGN ADC7 7 Read/Write R R Initial Value 0 0 14 - ADC6 6 R R 0 0 13 - ADC5 5 R R 0 0 12 - ADC4 4 R R 0 0 11 - ADC3 3 R R 0 0 10 - ADC2 2 R R 0 0 9 ADC9 ADC1 1 R R 0 0 8 ADC8 ADC0 0 R R 0 0 ADCH ADCL
ADLAR = 1
Bit $05 ($25) $04 ($24) 15 ADC9 ADC1 7 Read/Write R R Initial Value 0 0 14 ADC8 ADC0 6 R R 0 0 13 ADC7 - 5 R R 0 0 12 ADC6 - 4 R R 0 0 11 ADC5 - 3 R R 0 0 10 ADC4 - 2 R R 0 0 9 ADC3 - 1 R R 0 0 8 ADC2 - 0 R R 0 0 ADCH ADCL
When an ADC conversion is complete, the result is found in these two registers. When ADCL is read, the ADC Data Register is not updated until ADCH is read. Consequently, if the result is left adjusted and no more than 8-bit precision is required, it is sufficient to read ADCH. Otherwise, ADCL must be read first, then ADCH. The ADLAR bit in ADMUX affects the way the result is read from the registers. If ADLAR is set, the result is left adjusted. If ADLAR is cleared (default), the result is right adjusted. * ADC9..0: ADC Conversion Result These bits represent the result from the conversion. $000 represents analog ground, and $3FF represents the selected reference voltage minus one LSB.
134
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Scanning Multiple Channels
Since change of analog channel always is delayed until a conversion is finished, the Free Running mode can be used to scan multiple channels without interrupting the converter. Typically, the ADC Conversion Complete interrupt will be used to perform the channel shift. However, the user should take the following fact into consideration: The interrupt triggers once the result is ready to be read. In Free Running mode, the next conversion will start immediately when the interrupt triggers. If ADMUX is changed after the interrupt triggers, the next conversion has already started, and the old setting is used.
ADC Noise Canceling Techniques
Digital circuitry inside and outside the ATmega323 generates EMI which might affect the accuracy of analog measurements. If conversion accuracy is critical, the noise level can be reduced by applying the following techniques: 1. The analog part of the ATmega323 and all analog components in the application should have a separate analog ground plane on the PCB. This ground plane is connected to the digital ground plane via a single point on the PCB. 2. Keep analog signal paths as short as possible. Make sure analog tracks run over the analog ground plane, and keep them well away from high-speed switching digital tracks. 3. The AVCC pin on the ATmega323 should be connected to the digital VCC supply voltage via an LC network as shown in Figure 65. 4. Use the ADC noise canceler function to reduce induced noise from the CPU. 5. If some Port A pins are used as digital outputs, it is essential that these do not switch while a conversion is in progress. Figure 65. ADC Power Connections
Analog Ground Plane PA0 (ADC0) PA1 (ADC1) PA2 (ADC2) PA3 (ADC3)
39
GND
VCC
38
37
36
35
34 33 32 31 30 29 28 27 26 PA4 (ADC4)
PA5 (ADC5) PA6 (ADC6) PA7 (ADC7) AREF AGND AVCC
10 100nF
ATmega32
PC7
135
1457G-AVR-09/03
ADC Characteristics - Preliminary Data
Symbol Parameter Resolution Absolute accuracy Absolute accuracy Absolute accuracy Integral Non-linearity Differential Non-linearity Zero Error (Offset) Conversion Time Clock Frequency AVCC VREF VINT VBG RREF VIN RAIN Notes: Analog Supply Voltage Reference Voltage Internal Voltage Reference Bandgap Voltage Reference Reference Input Resistance Input Voltage Analog Input Resistance 1. Values are guidelines only. Actual values are TBD. 2. Minimum for AVCC is 2.7V. 3. Maximum for AVCC is 5.5V. Condition Single-ended Conversion VREF = 4V ADC clock = 200 kHz VREF = 4V ADC clock = 1 MHz VREF = 4V ADC clock = 2 MHz VREF > 2V VREF > 2V VREF > 2V Free Running Conversion 65 50 VCC - 0.3(2) 2V 2.35 1.12 6 AGND 100 2.56 1.22 10 Min(2) Typ 10 1 4 16 0.5 0.5 1 260 200 VCC + 0.3(3) AVCC 2.77 1.32 13 AREF 2 Max(3) Units Bits LSB LSB LSB LSB LSB LSB s kHz V V V V k V M
136
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
I/O Ports
All AVR ports have true Read-Modify-Write functionality when used as general digital I/O ports. This means that the direction of one port pin can be changed without unintentionally changing the direction of any other pin with the SBI and CBI instructions. The same applies for changing drive value (if configured as output) or enabling/disabling of pull-up resistors (if configured as input). Port A is an 8-bit bi-directional I/O port with optional internal pull-ups. Three I/O Memory address locations are allocated for Port A, one each for the Data Register - PORTA, $1B($3B), Data Direction Register - DDRA, $1A($3A) and the Port A Input Pins - PINA, $19($39). The Port A Input Pins address is read only, while the Data Register and the Data Direction Register are read/write. All port pins have individually selectable pull-up resistors. The Port A output buffers can sink 20 mA and thus drive LED displays directly. When pins PA0 to PA7 are used as inputs and are externally pulled low, they will source current if the internal pull-up resistors are activated. Port A has an alternate function as analog inputs for the ADC. If some Port A pins are configured as outputs, it is essential that these do not switch when a conversion is in progress. This might corrupt the result of the conversion. During Power-down mode, the Schmitt Trigger of the digital input is disconnected. This allows analog signals that are close to VCC/2 to be present during Power-down without causing excessive power consumption. The Port A Data Register - PORTA
Port A
Bit $1B ($3B) Read/Write Initial Value
7
PORTA7
6
PORTA6
5
PORTA5
4
PORTA4
3
PORTA3
2
PORTA2
1
PORTA1
0
PORTA0 PORTA
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
The Port A Data Direction Register - DDRA
Bit $1A ($3A) Read/Write Initial Value
7 DDA7 R/W 0
6 DDA6 R/W 0
5 DDA5 R/W 0
4 DDA4 R/W 0
3 DDA3 R/W 0
2 DDA2 R/W 0
1 DDA1 R/W 0
0 DDA0 R/W 0 DDRA
The Port A Input Pins Address - PINA
Bit $19 ($39) Read/Write Initial Value
7 PINA7 R N/A
6 PINA6 R N/A
5 PINA5 R N/A
4 PINA4 R N/A
3 PINA3 R N/A
2 PINA2 R N/A
1 PINA1 R N/A
0 PINA0 R N/A PINA
The Port A Input Pins address - PINA - is not a register, and this address enables access to the physical value on each Port A pin. When reading PORTA the Port A Data Latch is read, and when reading PINA, the logical values present on the pins are read.
137
1457G-AVR-09/03
Port A as General Digital I/O
All 8-bits in Port A are equal when used as digital I/O pins. PAn, General I/O pin: The DDAn bit in the DDRA Register selects the direction of this pin, if DDAn is set (one), PAn is configured as an output pin. If DDAn is cleared (zero), PAn is configured as an input pin. If PORTAn is set (one) when the pin configured as an input pin, the MOS pull up resistor is activated. To switch the pull up resistor off, the PORTAn has to be cleared (zero), the pin has to be configured as an output pin, or the PUD bit has to be set. The Port A pins are tri-stated when a reset condition becomes active, even if the clock is not running. Table 48. DDAn Effects on Port A Pins(1)
DDAn 0 0 0 1 1 Note: PORTAn 0 1 1 0 1 PUD (in SFIOR) X 0 1 X X I/O Input Input Input Output Output Pull Up No Yes No No No Comment Tri-state (Hi-Z) PAn will source current if ext. pulled low. Tri-state (Hi-Z) Push-pull Zero Output Push-pull One Output
1. n: 7,6...0, pin number.
Port A Schematics
Note that all port pins are synchronized. The synchronization latches are not shown in the figure. Figure 66. Port A Schematic Diagrams (Pins PA0 - PA7)
RD MOS PULLUP
PUD
RESET
Q
D
DDAn
C
RESET
PDn
Q D PORTAn C RL
WP
PWRDN
RP
TO ADC MUX WP: WD: RL: RP: RD: n: PUD: WRITE PORTA WRITE DDRA READ PORTA LATCH READ PORTA PIN READ DDRA 0-7 PULL-UP DISABLE
ADCn
138
ATmega323(L)
1457G-AVR-09/03
DATA BUS
WD
ATmega323(L)
Port B
Port B is an 8-bit bi-directional I/O port with optional internal pull-ups. Three I/O Memory address locations are allocated for Port B, one each for the Data Register - PORTB, $18($38), Data Direction Register - DDRB, $17($37) and the Port B Input Pins - PINB, $16($36). The Port B Input Pins address is read only, while the Data Register and the Data Direction Register are read/write. All port pins have individually selectable pull-up resistors. The Port B output buffers can sink 20 mA and thus drive LED displays directly. When pins PB0 to PB7 are used as inputs and are externally pulled low, they will source current if the internal pull-up resistors are activated. The Port B pins with alternate functions are shown in Table 49.: Table 49. Port B Pins Alternate Functions
Port Pin PB0 PB1 PB2 PB3 PB4 PB5 PB6 PB7 Alternate Functions T0 (Timer/Counter 0 External Counter Input) XCK (USART External Clock Input/Output) T1 (Timer/Counter 1 External Counter Input) AIN0 (Analog Comparator Positive Input) INT2 (External Interrupt 2 Input) AIN1 (Analog Comparator Negative Input) OC0 (Timer/Counter0 Output Compare Match Output) SS (SPI Slave Select Input) MOSI (SPI Bus Master Output/Slave Input) MISO (SPI Bus Master Input/Slave Output) SCK (SPI Bus Serial Clock)
When the pins are used for the alternate function, the DDRB and PORTB Registers have to be set according to the alternate function description. The Port B Data Register - PORTB
Bit $18 ($38) Read/Write Initial Value
7
PORTB7
6
PORTB6
5
PORTB5
4
PORTB4
3
PORTB3
2
PORTB2
1
PORTB1
0
PORTB0 PORTB
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
The Port B Data Direction Register - DDRB
Bit $17 ($37) Read/Write Initial Value
7 DDB7 R/W 0
6 DDB6 R/W 0
5 DDB5 R/W 0
4 DDB4 R/W 0
3 DDB3 R/W 0
2 DDB2 R/W 0
1 DDB1 R/W 0
0 DDB0 R/W 0 DDRB
The Port B Input Pins Address - PINB
Bit $16 ($36) Read/Write Initial Value
7 PINB7 R N/A
6 PINB6 R N/A
5 PINB5 R N/A
4 PINB4 R N/A
3 PINB3 R N/A
2 PINB2 R N/A
1 PINB1 R N/A
0 PINB0 R N/A PINB
139
1457G-AVR-09/03
The Port B Input Pins address - PINB - is not a register, and this address enables access to the physical value on each Port B pin. When reading PORTB, the Port B Data Latch is read, and when reading PINB, the logical values present on the pins are read. Port B As General Digital I/O All eight bits in Port B are equal when used as digital I/O pins. PBn, General I/O pin: The DDBn bit in the DDRB Register selects the direction of this pin, if DDBn is set (one), PBn is configured as an output pin. If DDBn is cleared (zero), PBn is configured as an input pin. If PORTBn is set (one) when the pin configured as an input pin, the MOS pull up resistor is activated. To switch the pull up resistor off, the PORTBn has to be cleared (zero), the pin has to be configured as an output pin, or the PUD bit has to be set. The Port B pins are tri-stated when a reset condition becomes active, even if the clock is not running. Table 50. DDBn Effects on Port B Pins(1)
DDBn 0 0 0 1 1 Note: PORTBn 0 1 1 0 1 PUD (in SFIOR) X 0 1 X X I/O Input Input Input Output Output Pull-up No Yes No No No Comment Tri-state (Hi-Z) PBn will Source Current if Ext. Pulled Low. Tri-state (Hi-Z) Push-Pull Zero Output Push-Pull One Output
1. n: 7,6...0, pin number.
Alternate Functions of Port B
The alternate pin configuration is as follows: * SCK - Port B, Bit 7 SCK: Master Clock output, Slave Clock input pin for SPI channel. When the SPI is enabled as a Slave, this pin is configured as an input regardless of the setting of DDB7. When the SPI is enabled as a Master, the data direction of this pin is controlled by DDB7. When the pin is forced to be an input, the pull-up can still be controlled by the PORTB7 bit. See the description of the SPI port for further details. * MISO - Port B, Bit 6 MISO: Master Data input, Slave Data output pin for SPI channel. When the SPI is enabled as a Master, this pin is configured as an input regardless of the setting of DDB6. When the SPI is enabled as a Slave, the data direction of this pin is controlled by DDB6. When the pin is forced to be an input, the pull-up can still be controlled by the PORTB6 bit. See the description of the SPI port for further details. * MOSI - Port B, Bit 5 MOSI: SPI Master Data output, Slave Data input for SPI channel. When the SPI is enabled as a Slave, this pin is configured as an input regardless of the setting of DDB5. When the SPI is enabled as a Master, the data direction of this pin is controlled by DDB5. When the pin is forced to be an input, the pull-up can still be controlled by the PORTB5 bit. See the description of the SPI port for further details.
140
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
* SS - Port B, Bit 4 SS: Slave Port Select input. When the SPI is enabled as a Slave, this pin is configured as an input regardless of the setting of DDB4. As a Slave, the SPI is activated when this pin is driven low. When the SPI is enabled as a Master, the data direction of this pin is controlled by DDB4. When the pin is forced to be an input, the pull-up can still be controlled by the PORTB4 bit. See the description of the SPI port for further details. * AIN1/OC0 - Port B, Bit 3 AIN1, Analog Comparator Negative Input. When configured as an input (DDB3 is cleared (zero)) and with the internal MOS pull up resistor switched off (PB3 is cleared (zero)), this pin also serves as the negative input of the On-chip Analog Comparator. During Power-down mode, the Schmitt Trigger of the digital input is disconnected. This allows analog signals which are close to VCC/2 to be present during Power-down without causing excessive power consumption. OC0, Output Compare Match output: The PB3 pin can serve as an external output for the Timer/Counter0 Compare Match. The PB3 pin has to be configured as an output (DDB3 set (one)) to serve this function. See "8-bit Timers/Counters Timer/Counter0 and Timer/Counter2" on page 45 for further details, and how to enable the output. The OC0 pin is also the output pin for the PWM mode timer function. * AIN0/INT2 - Port B, Bit 2 AIN0, Analog Comparator Positive Input. When configured as an input (DDB2 is cleared (zero)) and with the internal MOS pull up resistor switched off (PB2 is cleared (zero)), this pin also serves as the positive input of the On-chip Analog Comparator. During Power-down mode, the Schmitt Trigger of the digital input is disconnected if INT2 is not enabled. This allows analog signals which are close to VCC /2 to be present during Power-down without causing excessive power consumption. INT2, External Interrupt Source 2: The PB2 pin can serve as an external interrupt source to the MCU. See "MCU Control and Status Register - MCUCSR" on page 30 for further details. * T1 - Port B, Bit 1 T1, Timer/Counter1 Counter Source. See the timer description for further details. * T0/XCK - Port B, Bit 0 T0, Timer/Counter0 Counter Source. See the timer description for further details. XCK, USART external clock. See the USART description for further details.
141
1457G-AVR-09/03
Port B Schematics
Note that all port pins are synchronized. The synchronization latches are not shown in the figures. Figure 67. Port B Schematic Diagram (Pin PB0)
PUD
DDB0
UMSEL
PB0
1 0
XCK OUTPUT
PORTB0
TIMER0 CLOCK SOURCE MUX
PUD: PULL-UP DISABLE
CS02 CS01 CS00
XCK INPUT
Figure 68. Port B Schematic Diagram (Pin PB1)
PUD
DDB1
PB1
PORTB1
TIMER1 CLOCK SOURCE MUX
PUD: PULL-UP DISABLE
CS12 CS11 CS10
142
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Figure 69. Port B Schematic Diagram (Pin PB2)
RD MOS PULLUP
PUD
RESET R
Q
D
DDB2
C
RESET R Q D PORTB2 C RL
PB2
WP
INT2 ENABLE PWRDN
RP
'1' WP: WD: RL: RP: RD: PUD: WRITE PORTB WRITE DDRB READ PORTB LATCH READ PORTB PIN READ DDRB PULL-UP DISABLE ISC2
D C
Q
R HW CLEAR SW CLEAR
TO COMPARATOR
Figure 70. Port B Schematic Diagram (Pin PB3)
PUD
DDB3
PB3
PORTB3
PWRDN
WP: WD: RL: RP: RD: PUD:
WRITE PORTB WRITE DDRB READ PORTB LATCH READ PORTB PIN READ DDRB PULL-UP DISABLE
COM00 COM01 COMP. MATCH 0 PWM0 FOC0
DATA BUS
INT2 AIN0
WD
TO COMPARATOR
AIN1
143
1457G-AVR-09/03
Figure 71. Port B Schematic Diagram (Pin PB4)
RD MOS PULLUP
PUD
RESET
Q
D
DDB4
C
RESET
PB4
Q D PORTB4 C RL
WP
RP
WP: WD: RL: RP: RD: MSTR: SPE: PUD:
WRITE PORTB WRITE DDRB READ PORTB LATCH READ PORTB PIN READ DDRB SPI MASTER ENABLE SPI ENABLE PULL-UP DISABLE
MSTR SPE
SPI SS
Figure 72. Port B Schematic Diagram (Pin PB5)
RD MOS PULLUP
PUD
RESET R
Q
D
DDB5
C
RESET R Q D PORTB5 C RL
PB5
WP
RP
WP: WD: RL: RP: RD: SPE: MSTR: PUD:
WRITE PORTB WRITE DDRB READ PORTB LATCH READ PORTB PIN READ DDRB SPI ENABLE MASTER SELECT PULL-UP DISABLE
MSTR SPE SPI MASTER OUT
SPI SLAVE IN
144
ATmega323(L)
1457G-AVR-09/03
DATA BUS
WD
DATA BUS
WD
ATmega323(L)
Figure 73. Port B Schematic Diagram (Pin PB6)
RD MOS PULLUP
PUD
RESET R
Q
D
DDB6
C
RESET R Q D PORTB6 C RL
PB6
WP
RP
WP: WD: RL: RP: RD: SPE: MSTR PUD:
WRITE PORTB WRITE DDRB READ PORTB LATCH READ PORTB PIN READ DDRB SPI ENABLE MASTER SELECT PULL-UP DISABLE
MSTR SPE SPI SLAVE OUT
SPI MASTER IN
Figure 74. Port B Schematic Diagram (Pin PB7)
RD MOS PULLUP
PUD
RESET R
Q
D
DDB7
C
RESET R Q D PORTB7 C RL
PB7
WP
RP
WP: WD: RL: RP: RD: SPE: MSTR PUD:
WRITE PORTB WRITE DDRB READ PORTB LATCH READ PORTB PIN READ DDRB SPI ENABLE MASTER SELECT PULL-UP DISABLE
MSTR SPE SPI ClLOCK OUT
SPI CLOCK IN
DATA BUS
WD
DATA BUS
WD
145
1457G-AVR-09/03
Port C
Port C is an 8-bit bi-directional I/O port with optional internal pull-ups. Three I/O Memory address locations are allocated for the Port C, one each for the Data Register - PORTC, $15($35), Data Direction Register - DDRC, $14($34) and the Port C Input Pins - PINC, $13($33). The Port C Input Pins address is read only, while the Data Register and the Data Direction Register are read/write. All port pins have individually selectable pull-up resistors. The Port C output buffers can sink 20mA and thus drive LED displays directly. When pins PC0 to PC7 are used as inputs and are externally pulled low, they will source current if the internal pull-up resistors are activated. Table 51. Port C Pins Alternate Functions
Port Pin PC0 PC1 PC2 PC3 PC4 PC5 PC6 PC7 Alternate Function SCL (Two-wire Serial Bus Clock Line) SDA (Two-wire Serial Bus Data Input/Output Line) TCK (JTAG Test Clock) TMS (JTAG Test Mode Select) TDO (JTAG Test Data Out) TDI (JTAG Test Data In) TOSC1 (Timer Oscillator Pin 1) TOSC2 (Timer Oscillator Pin 2)
The Port C Data Register - PORTC
Bit $15 ($35) Read/Write Initial Value
7
PORTC7
6
PORTC6
5
PORTC5
4
PORTC4
3
PORTC3
2
PORTC2
1
PORTC1
0
PORTC0 PORTC
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
The Port C Data Direction Register - DDRC
Bit $14 ($34) Read/Write Initial Value
7 DDC7 R/W 0
6 DDC6 R/W 0
5 DDC5 R/W 0
4 DDC4 R/W 0
3 DDC3 R/W 0
2 DDC2 R/W 0
1 DDC1 R/W 0
0 DDC0 R/W 0 DDRC
The Port C Input Pins Address - PINC
Bit $13 ($33) Read/Write Initial Value
7 PINC7 R N/A
6 PINC6 R N/A
5 PINC5 R N/A
4 PINC4 R N/A
3 PINC3 R N/A
2 PINC2 R N/A
1 PINC1 R N/A
0 PINC0 R N/A PINC
The Port C Input Pins address - PINC - is not a register, and this address enables access to the physical value on each Port C pin. When reading PORTC, the Port C Data Latch is read, and when reading PINC, the logical values present on the pins are read. Port C As General Digital I/O All 8 bits in Port C are equal when used as digital I/O pins. PCn, General I/O pin: The DDCn bit in the DDRC Register selects the direction of this pin, if DDCn is set (one), PCn is configured as an output pin. If DDCn is cleared (zero), PCn is configured as an input pin. If PORTCn is set (one) when the pin configured as an input pin, the MOS pull up resistor is activated. To switch the pull up resistor off,
146
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
PORTCn has to be cleared (zero), the pin has to be configured as an output pin, or the PUD bit has to be set. The Port C pins are tri-stated when a reset condition becomes active, even if the clock is not running. Table 52. DDCn Effects on Port C Pins(1)
DDCn 0 0 0 1 1 Note: PORTCn 0 1 1 0 1 PUD (in SFIOR) X 0 1 X X I/O Input Input Input Output Output Pull-up No Yes No No No Comments Tri-state (Hi-Z) PCn will Source Current if Ext. Pulled Low. Tri-state (Hi-Z) Push-pull Zero Output Push-pull One Output
1. n: 7...0, pin number
If the JTAG Interface is enabled, the pull-up resistors on pins PC5 (TDI), PC3 (TMS) and PC2 (TCK) will be activated even if a reset occurs. Alternate Functions of Port C * TOSC2 - Port C, Bit 7 TOSC2, Timer Oscillator pin 2: When the AS2 bit in ASSR is set (one) to enable asynchronous clocking of Timer/Counter2, pin PC7 is disconnected from the port, and becomes the inverting output of the Oscillator amplifier. In this mode, a crystal Oscillator is connected to this pin, and the pin can not be used as an I/O pin. * TOSC1 - Port C, Bit 6 TOSC1, Timer Oscillator pin 1: When the AS2 bit in ASSR is set (one) to enable asynchronous clocking of Timer/Counter1, pin PC6 is disconnected from the port, and becomes the input of the inverting Oscillator amplifier. In this mode, a crystal Oscillator is connected to this pin, and the pin can not be used as an I/O pin. * TDI - Port C, Bit 5 TDI, JTAG Test Data In: Serial input data to be shifted in to the Instruction Register or Data Register (scan chains). When the JTAG interface is enabled, this pin can not be used as an I/O pin. Refer to the section "JTAG Interface and the On-chip Debug System" on page 157 for details on operation of the JTAG interface. * TDO - Port C, Bit 4 TDO, JTAG Test Data Out: Serial output data from Instruction Register or Data Register. When the JTAG interface is enabled, this pin can not be used as an I/O pin. Refer to the section "JTAG Interface and the On-chip Debug System" on page 157 for details on operation of the JTAG interface. * TMS - Port C, Bit 3 TMS, JTAG Test Mode Select: This pin is used for navigating through the TAP-controller state machine. When the JTAG interface is enabled, this pin can not be used as an I/O pin. Refer to the section "JTAG Interface and the On-chip Debug System" on page 157 for details on operation of the JTAG interface.
147
1457G-AVR-09/03
* TCK - Port C, Bit 2 TCK, JTAG Test Clock: JTAG operation is synchronous to TCK. When the JTAG interface is enabled, this pin can not be used as an I/O pin. Refer to the section "JTAG Interface and the On-chip Debug System" on page 157 for details on operation of the JTAG interface. * SDA - Port C, Bit 1 SDA, Two-wire Serial Interface Data: When the TWEN bit in TWCR is set (one) to enable the Two-wire Serial Interface, pin PC1 is disconnected from the port and becomes the Serial Data I/O pin for the Two-wire Serial Interface. In this mode, there is a spike filter on the pin to capture spikes shorter than 50 ns on the input signal, and the pin is driven by an open collector driver with slew rate limitation. * SCL - Port C, Bit 0 SCL, Two-wire Serial Interface Clock: When the TWEN bit in TWCR is set (one) to enable the Two-wire Serial Interface, pin PC1 is disconnected from the port and becomes the Serial Clock I/O pin for the Two-wire Serial Interface. In this mode, there is a spike filter on the pin to capture spikes shorter than 50 ns on the input signal. Port C Schematics Note that all port pins are synchronized. The synchronization latches are not shown in the figure. Figure 75. Port C Schematic Diagram (Pins PC0 - PC1)
0
DDCn
PUD
1 0 1
0
PCn
n
SCL/SDA out SCL/SDA in TWEN
PUD: PULL-UP DISABLE n = 0, 1
148
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Figure 76. Port C Schematic Diagram (Pins PC2 - PC5). The JTAG interface on these pins is not shown in the figure.
RD MOS PULLUP
PUD
RESET R
Q
D
DDCn
C
RESET R Q D PORTCn C RL
PCn
WP
RP
WP: WD: RL: RP: RD: PUD: n:
WRITE PORTC WRITE DDRC READ PORTC LATCH READ PORTC PIN READ DDRC PULL-UP DISABLE 2..5
Figure 77. Port C Schematic Diagram (Pins PC6)
RD MOS PULLUP
PUD
RESET R
Q
D
DDC6
C
RESET R Q D PORTC6 C RL
PC6
WP
RP 0 1 AS2 T/C2 OSC AMP INPUT WP: WD: RL: RP: RD: AS2: PUD: WRITE PORTC WRITE DDRC READ PORTC LATCH READ PORTC PIN READ DDRC ASYNCH SELECT T/C2 PULL-UP DISABLE
DATA BUS
WD
DATA BUS
WD
149
1457G-AVR-09/03
Figure 78. Port C Schematic Diagram (Pins PC7)
PUD
0 1
WP: WD: RL: RP: RD: AS2: PUD:
WRITE PORTC WRITE DDRC READ PORTC LATCH READ PORTC PIN READ DDRC ASYNCH SELECT T/C2 PULL-UP DISABLE
150
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Port D
Port D is an 8-bit bi-directional I/O port with optional internal pull-up resistors. Three I/O Memory address locations are allocated for Port D, one each for the Data Register - PORTD, $12($32), Data Direction Register - DDRD, $11($31) and the Port D Input Pins - PIND, $10($30). The Port D Input Pins address is read only, while the Data Register and the Data Direction Register are read/write. The Port D output buffers can sink 20 mA. As inputs, Port D pins that are externally pulled low will source current if the pull-up resistors are activated. Some Port D pins have alternate functions as shown in Table 53. Table 53. Port D Pins Alternate Functions
Port Pin PD0 PD1 PD2 PD3 PD4 PD5 PD6 PD7 Alternate Function RXD (USART Input Pin) TXD (USART Output Pin) INT0 (External Interrupt 0 Input) INT1 (External Interrupt 1 Input) OC1B (Timer/Counter1 Output Compare B Match Output) OC1A (Timer/Counter1 Output Compare A Match Output) ICP (Timer/Counter1 Input Capture Pin) OC2 (Timer/Counter2 Output Compare Match Output)
The Port D Data Register - PORTD
Bit $12 ($32) Read/Write Initial ue Val-
7
PORTD7
6
PORTD6
5
PORTD5
4
PORTD4
3
PORTD3
2
PORTD2
1
PORTD1
0
PORTD0 PORTD
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
The Port D Data Direction Register - DDRD
Bit $11 ($31) Read/Write Initial Value
7 DDD7 R/W 0
6 DDD6 R/W 0
5 DDD5 R/W 0
4 DDD4 R/W 0
3 DDD3 R/W 0
2 DDD2 R/W 0
1 DDD1 R/W 0
0 DDD0 R/W 0 DDRD
The Port D Input Pins Address - PIND
Bit $10 ($30) Read/Write Initial Value
7 PIND7 R N/A
6 PIND6 R N/A
5 PIND5 R N/A
4 PIND4 R N/A
3 PIND3 R N/A
2 PIND2 R N/A
1 PIND1 R N/A
0 PIND0 R N/A PIND
The Port D Input Pins address - PIND - is not a register, and this address enables access to the physical value on each Port D pin. When reading PORTD, the Port D Data Latch is read, and when reading PIND, the logical values present on the pins are read.
151
1457G-AVR-09/03
Port D As General Digital I/O
PDn, General I/O pin: The DDDn bit in the DDRD Register selects the direction of this pin. If DDDn is set (one), PDn is configured as an output pin. If DDDn is cleared (zero), PDn is configured as an input pin. If PDn is set (one) when configured as an input pin the MOS pull up resistor is activated. To switch the pull up resistor off the PDn has to be cleared (zero), the pin has to be configured as an output pin, or the PUD bit has to be set. The Port D pins are tri-stated when a reset condition becomes active, even if the clock is not running. Table 54. DDDn Effects on Port D Pins
DDDn 0 0 0 1 1 Note: PORTDn 0 1 1 0 1 PUD (in SFIOR) X 0 1 X X I/O Input Input Input Output Output Pull Up No Yes No No No Comment Tri-state (Hi-Z) PDn will Source Current if Ext. Pulled Low. Tri-state (Hi-Z) Push-pull Zero Output Push-pull One Output
n: 7,6...0, pin number.
Alternate Functions of Port D
* OC2 - Port D, Bit 7 OC2, Timer/Counter2 Output Compare Match output: The PD7 pin can serve as an external output for the Timer/Counter2 Output Compare. The pin has to be configured as an output (DDD7 set (one)) to serve this function. See the timer description on how to enable this function. The OC2 pin is also the output pin for the PWM mode timer function. * ICP - Port D, Bit 6 ICP - Input Captur e Pin: The PD6 pin can act as an Input Capture Pin for Timer/Counter1. The pin has to be configured as an input (DDD6 cleared(zero)) to serve this function. See the timer description on how to enable this function. * OC1A - Port D, Bit 5 OC1A, Output Compare Match A output: The PD5 pin can serve as an external output for the Timer/Counter1 Output Compare A. The pin has to be configured as an output (DDD5 set (one)) to serve this function. See the timer description on how to enable this function. The OC1A pin is also the output pin for the PWM mode timer function. * OC1B - Port D, Bit 4 OC1B, Output Compare Match B output: The PD4 pin can serve as an external output for the Timer/Counter1 Output Compare B. The pin has to be configured as an output (DDD4 set (one)) to serve this function. See the timer description on how to enable this function. The OC1B pin is also the output pin for the PWM mode timer function. * INT1 - Port D, Bit 3 INT1, External Interrupt Source 1: The PD3 pin can serve as an external interrupt source to the MCU. See the interrupt description for further details, and how to enable the source.
152
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
* INT0 - Port D, Bit 2 INT0, External Interrupt Source 0: The PD2 pin can serve as an external interrupt source to the MCU. See the interrupt description for further details, and how to enable the source. * TXD - Port D, Bit 1 TXD, Transmit Data (Data output pin for the USART). When the USART Transmitter is enabled, this pin is configured as an output regardless of the value of DDD1. * RXD - Port D, Bit 0 RXD, Receive Data (Data input pin for the USART). When the USART Receiver is enabled this pin is configured as an input regardless of the value of DDD0. When the USART forces this pin to be an input, a logical one in PORTD0 will turn on the internal pull-up. Port D Schematics Note that all port pins are synchronized. The synchronization latches are not shown in the figures. Figure 79. Port D Schematic Diagram (Pin PD0)
RD MOS PULLUP
PUD
RESET
Q
D
DDD0
C
RESET
PD0
Q D PORTD0 C RL
WP
RP
WP: WD: RL: RP: RD: RXD: RXEN: PUD:
WRITE PORTD WRITE DDRD READ PORTD LATCH READ PORTD PIN READ DDRD UART RECEIVE DATA UART RECEIVE ENABLE PULL-UP DISABLE
RXEN RXD
DATA BUS
WD
153
1457G-AVR-09/03
Figure 80. Port D Schematic Diagram (Pin PD1)
RD MOS PULLUP
PUD
RESET R
Q
D
DDD1
C
RESET R Q D PORTD1 C RL
PD1
WP
RP
WP: WD: RL: RP: RD: TXD: TXEN: PUD:
WRITE PORTD WRITE DDRD READ PORTD LATCH READ PORTD PIN READ DDRD UART TRANSMIT DATA UART TRANSMIT ENABLE PULL-UP DISABLE
TXEN TXD
Figure 81. Port D Schematic Diagram (Pins PD2 and PD3)
PUD
WP: WD: RL: RP: RD: PUD: n: m:
WRITE PORTD WRITE DDRD READ PORTD LATCH READ PORTD PIN READ DDRD PULL-UP DISABLE 2, 3 0, 1
154
ATmega323(L)
1457G-AVR-09/03
DATA BUS
WD
ATmega323(L)
Figure 82. Port D Schematic Diagram (Pins PD4 and PD5)
PUD
WP: WD: RL: RP: RD: PUD:
WRITE PORTD WRITE DDRD READ PORTD LATCH READ PORTD PIN READ DDRD PULL-UP DISABLE
Figure 83. Port D Schematic Diagram (Pin PD6)
RD MOS PULLUP
PUD
RESET R
Q
D
DDD6
C
RESET R Q D PORTD6 C RL
PD6
WP
RP
WP: WD: RL: RP: RD: ACIC: ACO: PUD:
WRITE PORTD WRITE DDRD READ PORTD LATCH READ PORTD PIN READ DDRD COMPARATOR IC ENABLE COMPARATOR OUTPUT PULL-UP DISABLE
0 NOISE CANCELER 1 ICNC1 ICES1 ACIC ACO EDGE SELECT ICF1
DATA BUS
WD
155
1457G-AVR-09/03
Figure 84. Port D Schematic Diagram (Pin PD7)
PUD
WP: WD: RL: RP: RD: PUD:
WRITE PORTD WRITE DDRD READ PORTD LATCH READ PORTD PIN READ DDRD PULL-UP DISABLE
156
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
JTAG Interface and the On-chip Debug System
Features
* JTAG (IEEE std. 1149.1 Compliant) Interface * Boundary-Scan Capabilities According to the JTAG Standard * Debugger Access to:
- All Internal Peripheral Units - Internal and External RAM - The Internal Register File - Program Counter - EEPROM and Flash Memories * Extensive On-chip Debug Support for Break Conditions, Including - Break on Change of Program Memory Flow - Single Step Break - Program Memory Break Points on Single Address or Address Range - Data Memory Break Points on Single Address or Address Range * Programming of Flash, EEPROM, Fuses, and Lock Bits through the JTAG Interface * On-chip Debugging Supported by AVR Studio(R)
Overview
The AVR IEEE std. 1149.1 compliant JTAG interface can be used for * * * Testing PCBs by using the JTAG Boundary-Scan Capability. Programming the Non-volatile Memories, Fuses and Lock bits. On-chip Debugging.
A brief description is given in the following sections. Detailed descriptions for Programming via the JTAG interface, and using the Boundary-Scan Chain can be found in the sections "Programming via the JTAG Interface" on page 202 and "IEEE 1149.1 (JTAG) Boundary-Scan" on page 164, respectively. The On-chip Debug support is considered being private JTAG instructions, and distributed within ATMEL and to selected third party vendors only. Figure 85 shows a block diagram of the JTAG interface and the On-chip Debug system. The TAP Controller is a state machine controlled by the TCK and TMS signals. The TAP Controller selects either the JTAG Instruction Register or one of several Data Registers as the scan chain (Shift Register) between the TDI - input and TDO - output. The Instruction Register holds JTAG instructions controlling the behavior of a Data Register. Of the Data Registers, the ID-Register, Bypass Register, and the Boundary-Scan Chain are used for board-level testing. The JTAG Programming Interface (actually consisting of several physical and virtual Data Registers) is used for Serial Programming via the JTAG interface. The Internal Scan Chain and Break Point Scan Chain are used for Onchip debugging only.
157
1457G-AVR-09/03
The Test Access Port - TAP
The JTAG interface is accessed through four of the AVR's pins. In JTAG terminology, these pins constitute the Test Access Port - TAP. These pins are * * * * TMS: Test mode select. This pin is used for navigating through the TAP-controller state machine. TCK: Test clock. JTAG operation is synchronous to TCK TDI: Test Data In. Serial input data to be shifted in to the Instruction Register or Data Register (Scan Chains) TDO: Test Data Out. Serial output data from Instruction Register or Data Register
The IEEE std. 1149.1 also specifies an optional TAP signal; TRST - Test ReSeT - which is not provided. When the JTAGEN fuse is unprogrammed, these four TAP pins are normal port pins and the TAP controller is in reset. When programmed and the JTD bit in MCUCSR is cleared, the TAP input signals are internally pulled high and the JTAG is enabled for Boundary-scan and programming. In this case, the TAP output pin (TDO) is left floating in states where the JTAG TAP controller is not shifting data, and must therefore be connected to a pull-up resistor or other hardware having pull-ups (for instance the TDI-input of the next device in the scan chain). The device is shipped with this fuse programmed. For the On-chip Debug system, in addition the RESET pin is monitored by the debugger to be able to detect External Reset sources. The debugger can also pull the RESET pin low to reset the whole system, assuming only open collectors on reset line are used in the application.
158
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Figure 85. Block Diagram
PORT A
DEVICE BOUNDARY
BOUNDARY SCAN CHAIN
TDI TDO TCK TMS
TAP CONTROLLER
JTAG PROGRAMMING INTERFACE
AVR CPU INSTRUCTION REGISTER ID REGISTER M U X BYPASS REGISTER FLASH MEMORY Address Data INTERNAL SCAN CHAIN PC Instruction
BREAKPOINT UNIT
DIGITAL PERIPHERAL UNITS
ANALOG PERIPHERIAL UNITS
BREAKPOINT SCAN CHAIN ADDRESS DECODER JTAG / AVR CORE COMMUNICATION INTERFACE
OCD STATUS AND CONTROL
PORT B
1457G-AVR-09/03
Control & Clock lines
Analog inputs
FLOW CONTROL UNIT
159
Figure 86. TAP Controller State Diagram
1 Test-Logic-Reset 0 0 Run-Test/Idle 1 Select-DR Scan 0 1 Capture-DR 0 Shift-DR 1 Exit1-DR 0 Pause-DR 1 0 Exit2-DR 1 Update-DR 1 0 0 0 1 0 1 1 Select-IR Scan 0 Capture-IR 0 Shift-IR 1 Exit1-IR 0 Pause-IR 1 Exit2-IR 1 Update-IR 1 0 0 1 0 1
TAP Controller
The TAP controller is a 16-state finite state machine that controls the operation of the Boundary-Scan circuitry, JTAG programming circuitry, or On-chip Debug system. The state transitions depicted in Figure 86 depends on the signal present on TMS (shown adjacent to each state transition) at the time of the rising edge at TCK. The initial state after a Power-On Reset is Test-Logic-Reset. As a definition in this document, the LSB is shifted in and out first for all Shift Registers. Assuming Run-Test/Idle is the present state, a typical scenario for using the JTAG interface is * At the TMS input, apply the sequence 1, 1, 0, 0 at the rising edges of TCK to enter the Shift Instruction Register - Shift-IR state. While TMS is low, shift the 4-bit JTAG instructions into the JTAG Instruction Register from the TDI input at the rising edge of TCK, while the captured IR-state 0x01 is shifts out on the TDO pin. The JTAG Instruction selects a particular Data Register as path between TDI and TDO and controls the circuitry surrounding the selected Data Register.
160
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
* Apply the TMS sequence 1, 1, 0 to re-enter the Run-Test/Idle state. The instruction is latched onto the parallel output from the Shift Register path in the Update-IR state. The Exit-IR, Pause-IR, and Exit2-IR states are only used for navigating the state machine. At the TMS input, apply the sequence 1, 0, 0 at the rising edges of TCK to enter the Shift Data Register - Shift-DR state. While TMS is low, upload the selected Data Register (selected by the present JTAG instruction in the JTAG Instruction Register) from the TDI input at the rising edge of TCK. At the same time, the parallel inputs to the Data Register captured in the Capture-DR state shifts out on the TDO pin. Apply the TMS sequence 1, 1, 0 to re-enter the Run-Test/Idle state. If the selected Data Register has a latched parallel-output, the latching takes place in the UpdateDR state. The Exit-DR, Pause-DR, and Exit2-DR states are only used for navigating the state machine.
*
*
As shown in the state diagram, the Run-Test/Idle state need not be entered between selecting JTAG instruction and using Data Registers, and some JTAG instructions may select certain functions to be performed in the Run-Test/Idle, making it unsuitable as an Idle state.
Note: Independent of the initial state of the TAP Controller, the Test-Logic-Reset state can always be entered by holding TMS high for 5 TCK clock periods.
For detailed information on the JTAG specification, refer to the literature listed in "Bibliography" on page 163.
Using the BoundaryScan Chain
A complete description of the Boundary-Scan capabilities are given in the section "IEEE 1149.1 (JTAG) Boundary-Scan" on page 164.
Using the On-chip Debug As shown in Figure 85, the hardware support for On-chip Debugging consists mainly of System * A scan chain on the interface between the internal AVR CPU and the internal
peripheral units. * * Break Point unit. Communication interface between the CPU and JTAG system.
All read or modify/write operations needed for implementing the Debugger are done by applying AVR instructions via the internal AVR CPU Scan Chain. The CPU sends the result to an I/O Memory mapped location which is part of the communication interface between the CPU and the JTAG system. The Break Point Unit implements Break on Change of Program Flow, Single Step Break, two Program memory Break Points, and two combined Break Points. Together, the 4 Break Points can be configured as either: * * * * * 4 single Program memory Break Points 3 Single Program memory Break Point + 1 single Data memory Break Point 2 single Program memory Break Points + 2 single Data memory Break Points 2 single Program memory Break Points + 1 Program memory Break Point with mask (`range Break Point') 2 single Program memory Break Points + 1 Data memory Break Point with mask (`range Break Point')
A list of the On-chip Debug specific JTAG instructions is given in "On-chip Debug Specific JTAG Instructions" on page 162. Note that Atmel supports the On-chip Debug system with the AVR Studio front-end software for PCs. The details on hardware imple-
161
1457G-AVR-09/03
mentation and JTAG instructions are therefore irrelevant for the user of the On-chip Debug system. The JTAGEN Fuse must be programmed to enable the JTAG Test Access Port. In addition, the OCDEN Fuse must be programmed and no Lock bits must be set for the Onchip debug system to work. The disabling of the On-chip debug system when any Lock bits are set is a security feature. Otherwise, the On-chip debug system would have provided a back-door into a secured device. The AVR Studio enables the user to fully control execution of programs on an AVR device with On-chip Debug capability, AVR In-Circuit Emulator, or the built-in AVR Instruction Set Simulator. AVR Studio supports source level execution of Assembly programs assembled with Atmel Corporation's AVR Assembler and C programs compiled with 3rd party vendors' compilers. AVR Studio runs under Microsoft(R) Windows(R) 95/98/2000 and Microsoft Windows NT(R). For a full description of the AVR Studio, please refer to the AVR Studio User Guide. Only highlights are presented in this document. All necessary execution commands are available in AVR Studio, both on source level and on disassembly level. The user can execute the program, single step through the code either by tracing into or stepping over functions, step out of functions, place the cursor on a statement and execute until the statement is reached, stop the execution, and reset the execution target. In addition, the user can have up to two Data memory Break Points, alternatively combined as a mask (range) Break Point.
On-chip Debug Specific JTAG Instructions
PRIVATE0; $8 PRIVATE1; $9 PRIVATE2; $A PRIVATE3; $B
The On-chip debug support is considered being private JTAG instructions, and distributed within ATMEL and to selected third party vendors only. Instruction opcode listed for reference. Private JTAG instruction for accessing On-chip debug system. Private JTAG instruction for accessing On-chip debug system. Private JTAG instruction for accessing On-chip debug system. Private JTAG instruction for accessing On-chip debug system.
162
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Using the JTAG Programming Capabilities
Programming of AVR parts via JTAG is performed via the 4-pin JTAG port, TCK, TMS, TDI and TDO. These are the only pins that need to be controlled/observed to perform JTAG programming (in addition to power pins). It is not required to apply 12V externally. The JTAGEN Fuse must be programmed and the JTD bit in the MCUSR Register must be cleared to enable the JTAG Test Access Port. The JTAG programming capability supports: * * * * Flash programming and verifying EEPROM programming and verifying Fuse programming and verifying Lock bit programming and verifying
The lock bit security is exactly as in parallel programming mode. If the Lock bits LB1 or LB2 are programmed, the OCDEN Fuse cannot be programmed unless first doing a chip erase. This is a security feature that ensures no back-door exists for reading out the content of a secured device. A description of the programming specific JTAG instructions is given in "Programming specific JTAG instructions" on page 202. The details on programming through the JTAG interface is given in the section "Programming via the JTAG Interface" on page 202 Bibliography For more information about general Boundary-Scan, the following literature can be consulted: * * IEEE: IEEE Std 1149.1-1990. IEEE Standard Test Access Port and Boundary-Scan Architecture, IEEE, 1993 Colin Maunder: The Board Designers Guide to Testable Logic Circuits, AddisonWesley, 1992
163
1457G-AVR-09/03
IEEE 1149.1 (JTAG) Boundary-Scan
Features
* * * * *
JTAG (IEEE std. 1149.1 compliant) Interface Boundary-Scan Capabilities According to the JTAG Standard Full Scan of All Port Functions Supports the Optional IDCODE Instruction Additional Public AVR_RESET Instruction to Reset the AVR
System Overview
The Boundary-Scan chain has the capability of driving and observing the logic levels on the digital I/O pins. At system level, all ICs having JTAG capabilities are connected serially by the TDI/TDO signals to form a long Shift Register. An external controller sets up the devices to drive values at their output pins, and observe the input values received from other devices. The controller compares the received data with the expected result. In this way, Boundary-Scan provides a mechanism for testing interconnections and integrity of components on Printed Circuits Boards by using the four TAP signals only. The four IEEE 1149.1 defined mandatory JTAG instructions IDCODE, BYPASS, SAMPLE/PRELOAD, and EXTEST, as well as the AVR specific public JTAG instruction AVR_RESET can be used for testing the Printed Circuit Board. Initial scanning of the Data Register path will show the ID-Code of the device, since IDCODE is the default JTAG instruction. It may be desirable to have the AVR device in reset during Test mode. If not reset, inputs to the device may be determined by the scan operations, and the internal software may be in an undetermined state when exiting the test mode. Entering Reset, the outputs of any Port Pin will instantly enter the high impedance state, making the HIGHZ instruction redundant. If needed, the BYPASS instruction can be issued to make the shortest possible scan chain through the device. The device can be set in the reset state either by pulling the external RESET pin low, or issuing the AVR_RESET instruction with appropriate setting of the Reset Data Register. The EXTEST instruction is used for sampling external pins and loading output pins with data. The data from the output latch will be driven out on the pins as soon as the EXTEST instruction is loaded into the JTAG IR-Register. Therefore, the SAMPLE/PRELOAD should also be used for setting initial values to the scan ring, to avoid damaging the board when issuing the EXTEST instruction for the first time. SAMPLE/PRELOAD can also be used for taking a snapshot of the external pins during normal operation of the part. The JTAGEN Fuse must be programmed and the JTD bit in the I/O Register MCUSR must be cleared to enable the JTAG Test Access Port. When using the JTAG interface for Boundary-Scan, using a JTAG TCK clock frequency higher than the internal chip frequency is possible. The chip clock is not required to run.
164
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Data Registers
The Data Registers are selected by the JTAG Instruction Registers described in section "Boundary-Scan Specific JTAG Instructions" on page 166. The Data Registers relevant for Boundary-Scan operations are: * * * * Bypass Register Bypass Register Device Identification Register Reset Register Boundary-Scan Chain
The Bypass Register consists of a single Shift Register stage. When the Bypass Register is selected as path between TDI and TDO, the register is reset to 0 when leaving the Capture-DR controller state. The Bypass Register can be used to shorten the scan chain on a system when the other devices are to be tested. Figure 87 shows the structure of the Device Identification Register. Figure 87. The format of the Device Identification Register
MSB Bit Device ID 31 28 27 12 11 Manufacturer ID 11 bits 1 LSB 0 1 1 bit
Device Identification Register
Version 4 bits
Part Number 16 bits
Version
Version is a 4-bit number identifying the revision of the component. The relevant version numbers are shown in Table 55. Table 55. JTAG Version Numbers
Version ATmega323 revision B JTAG Version number (Binary digits) 0010
Part Number
The part number is a 16 bit code identifying the component. The JTAG Part Number for AVR devices are listed in Table 56. Table 56. AVR JTAG Part Number
Part number ATmega323 JTAG Part Number (Hex) 0x9501
Manufacturer ID
The manufacturer ID for ATMEL is 0x01F (11 bit).
165
1457G-AVR-09/03
Reset Register
The Reset Register is a Test Data Register used to reset the part. Since the AVR tristates Port Pins when reset, the Reset Register can also replace the function of the unimplemented optional JTAG instruction HIGHZ. A high value in the Reset Register corresponds to pulling the external Reset low. The part is reset as long as there is a high value present in the Reset Register. Depending on the Fuse settings for the clock options, the part will remain reset for a Reset TimeOut Period (refer to Table 6 on page 27) after releasing the Reset Register. The output from this Data Register is not latched, so the reset will take place immediately, as shown in Figure 88. Figure 88. Reset Register
To TDO
From other internal and external reset sources From TDI Internal reset
D
Q
ClockDR * AVR_RESET
Boundary-Scan Chain
The Boundary-Scan Chain has the capability of driving and observing the logic levels on the digital I/O pins. See "Boundary-Scan Chain" on page 168 for a complete description.
Boundary-Scan Specific JTAG Instructions
The Instruction Register is four bit wide, supporting up to 16 instructions. Listed below are the JTAG instructions useful for Boundary-Scan operation. Note that the optional HIGHZ instruction is not implemented, but all outputs with tri-state capability can be set in high-impedant state by using the AVR_RESET instruction, since the initial state for all port pins is tri-state. As a definition in this datasheet, the LSB is shifted in and out first for all Shift Registers. The OPCODE for each instruction is shown behind the instruction name in hex format. The text describes which Data Register is selected as path between TDI and TDO for each instruction.
EXTEST; $0
Mandatory JTAG instruction for selecting the Boundary-Scan Chain as Data Register for testing circuitry external to the AVR package. For port-pins, Pull-up Disable, Output Control, Output Data, and Input Data are all accessible in the scan chain. For Analog circuits having Off-chip connections, the interface between the analog and the digital logic is in the scan chain. The contents of the latched outputs of the Boundary-Scan chain is driven out as soon as the JTAG IR-Register is loaded by the EXTEST instruction. The active states are: * * Capture-DR: Data on the external pins are sampled into the Boundary-Scan Chain. Shift-DR: The Internal Scan Chain is shifted by the TCK input.
166
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
* IDCODE; $1 Update-DR: Data from the scan chain is applied to output pins.
Optional JTAG instruction selecting the 32 bit ID Register as Data Register. The ID Register consists of a version number, a device number and the manufacturer code chosen by JEDEC. This is the default instruction after Power-up. The active states are: * * Capture-DR: Data in the IDCODE Register is sampled into the Boundary-Scan Chain. Shift-DR: The IDCODE scan chain is shifted by the TCK input.
SAMPLE_PRELOAD; $2
Mandatory JTAG instruction for pre-loading the output latches and taking a snap-shot of the input/output pins without affecting the system operation. However, the output latches are not connected to the pins. The Boundary-Scan Chain is selected as Data Register. The active states are: * * * Capture-DR: Data on the external pins are sampled into the Boundary-Scan Chain. Shift-DR: The Boundary-Scan Chain is shifted by the TCK input. Update-DR: Data from the Boundary-Scan chain is applied to the output latches. However, the output latches are not connected to the pins.
AVR_RESET; $C
The AVR specific public JTAG instruction for forcing the AVR device into the Reset mode or releasing the JTAG Reset source. The TAP controller is not reset by this instruction. The one bit Reset Register is selected as Data Register. Note that the reset will be active as long as there is a logic 'one' in the Reset Chain. The output from this chain is not latched. The active states are: * Shift-DR: The Reset Register is shifted by the TCK input.
BYPASS; $F
Mandatory JTAG instruction selecting the Bypass Register for Data Register. The active states are: * * Capture-DR: Loads a logic "0" into the Bypass Register. Shift-DR: The Bypass Register cell between TDI and TDO is shifted.
167
1457G-AVR-09/03
Boundary-Scan Chain
The Boundary-Scan chain has the capability of driving and observing the logic levels on the digital I/O pins.
Note: Compatibility issues regarding future devices: Future devices, included replacements for ATmega323 will have Pull-Up Enable signals instead of the Pull-Up Disable signals in the scan path (i.e. inverted logic). The scan cell for the reset signal will have the same logic level as the external pin (i.e. inverted logic). The length of the scan-chain is likely to change in future devices.
Scanning the Digital Port Pins
Figure 89 shows the Boundary-Scan Cell for Bidirectional Port Pins with Pull-up function. The cell consists of a standard Boundary-Scan cell for the Pull-up function, and a Bidirectional pin cell that combines the three signals Output Control - OC, Output Data - OD, and Input Data - ID, into only a two-stage Shift Register. Figure 89. Boundary-Scan Cell For bidirectional Port Pin with Pull-up Function.
ShiftDR To Next Cell EXTEST Vcc
Pullup Disable (PLD) FF2 0 D 1 G Q D Q LD2
0 1
Output Control (OC) FF1 0 D 1 G Q D Q LD1 0 1
Output Data (OD) Port Pin (PXn)
0 1 0
FF0 D 1 Q
LD0 D G Q
0 1
Input Data (ID)
From Last Cell
ClockDR
UpdateDR
The Boundary-Scan logic is not included in the figures in the datasheet. Figure 90 shows a simple digital Port Pin as described in the section "I/O Ports" on page 137. The Boundary-Scan details from Figure 89 replaces the dashed box in Figure 90.
168
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Figure 90. General Port Pin Schematic diagram
See Boundary Scan description for details
RD MOS PULLUP
PLD
PUD
RESET
Q
D
DDXn
C
OC
RESET
PXn
OD
Q D PORTXn C RL
ID
WP
RP
WP: WD: RL: RP: RD: n: PUD:
WRITE PORTX WRITE DDRX READ PORTX LATCH READ PORTX PIN READ DDRX 0-7 PULL-UP DISABLE
PuD: JTAG PULL-UP DISABLE OC: JTAG OUTPUT CONTROL OD: JTAG OUTPUT DATA ID: JTAG INPUT DATA
When no alternate port function is present, the Input Data - ID corresponds to the PINn Register value, Output Data corresponds to the PORTn Register, Output Control corresponds to the Data Direction - DDn Register, and the PuLL-up Disable - PLD - corresponds to logic expression (DDn OR NOT(PORTBn)). Digital alternate port functions are connected outside the dotted box in Figure 90 to make the scan chain read the actual pin value. For Analog function, there is a direct connection from the external pin to the analog circuit, and a scan chain is inserted on the interface between the digital logic and the analog circuit. Scanning RESET The RESET pin accepts 5V active low logic for standard reset operation. An observeonly cell as shown in Figure 91 is inserted at the output from the Reset Detector; RST.
Note: The scanned signal is active high, i.e., the RST signal is the inverse of the external RESET pin.
DATA BUS
WD
169
1457G-AVR-09/03
Figure 91. Observe-only Cell
To next cell
ShiftDR
From system pin
To system logic
FF1
0 D 1 Q
From previous cell
ClockDR
Internal signals
ATmega323 contains a lot of scan chains for internal signals. The description of these signals are not public. However, the user must apply safe values to these cells before applying the Update-DR state of the TAP controller.
Note: Incorrect setting of the scan cells for internal signals may cause signal contention and can damage the part. Make sure the safe values are used.
Table 57. Boundary-Scan signals for the ADC
Signal Name SIG_PRIVATE0 SIG_PRIVATE1 SIG_PRIVATE2 SIG_PRIVATE3 SIG_PRIVATE4 SIG_PRIVATE5 SIG_PRIVATE6 SIG_PRIVATE7 SIG_PRIVATE8 SIG_PRIVATE9 SIG_PRIVATE10 SIG_PRIVATE11 SIG_PRIVATE12 SIG_PRIVATE13 SIG_PRIVATE14 SIG_PRIVATE15 SIG_PRIVATE16 SIG_PRIVATE17 Type of scan cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell Recommended input when not in use 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0
170
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Table 57. Boundary-Scan signals for the ADC (Continued)
Signal Name SIG_PRIVATE18 SIG_PRIVATE19 SIG_PRIVATE20 SIG_PRIVATE21 SIG_PRIVATE22 SIG_PRIVATE23 SIG_PRIVATE24 SIG_PRIVATE25 SIG_PRIVATE26 SIG_PRIVATE27 SIG_PRIVATE28 SIG_PRIVATE29 SIG_PRIVATE30 SIG_PRIVATE31 SIG_PRIVATE32 SIG_PRIVATE33 SIG_PRIVATE34 SIG_PRIVATE35 SIG_PRIVATE36 SIG_PRIVATE37 SIG_PRIVATE38 SIG_PRIVATE39 SIG_PRIVATE40 SIG_PRIVATE41 SIG_PRIVATE42 SIG_PRIVATE43 SIG_PRIVATE44 SIG_PRIVATE45 SIG_PRIVATE46 Type of scan cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell General Scan Cell Observe Only Observe Only Observe Only Observe Only Recommended input when not in use 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 1 1 0 0 0 X X X X
171
1457G-AVR-09/03
ATmega323 BoundaryScan Order
Table 64 shows the Scan order between TDI and TDO when the Boundary-Scan chain is selected as data path. Bit 0 is the LSB; The first bit scanned in, and the first bit scanned out. The scan order follows the pinout order as far as possible. Therefore, the bits of Port A is scanned in the opposite bit order of the other ports. Exceptions from the rules are the Scan chains for the analog circuits, which constitute the most significant bits of the scan chain regardless of which physical pin they are connected to. In Figure 89, PXn.Data corresponds to FF0, PXn.Control corresponds to FF1, and PXn. Pullup_dissable corresponds to FF2. Bit 2, 3, 4, and 5 of Port C is not in the scan chain, since these pins constitute the TAP pins when the JTAG is enabled Table 58. ATmega323 Boundary-Scan Order
Bit Number 131 130 129 128 127 126 125 124 123 122 121 120 119 118 117 116 115 114 113 112 111 110 109 108 107 106 105 Signal Name SIG_PRIVATE0 SIG_PRIVATE1 Private Section 1 SIG_PRIVATE2 SIG_PRIVATE3 SIG_PRIVATE4 SIG_PRIVATE5 SIG_PRIVATE6 SIG_PRIVATE7 SIG_PRIVATE8 SIG_PRIVATE9 SIG_PRIVATE10 SIG_PRIVATE11 SIG_PRIVATE12 SIG_PRIVATE13 SIG_PRIVATE14 SIG_PRIVATE15 SIG_PRIVATE16 SIG_PRIVATE17 SIG_PRIVATE18 SIG_PRIVATE19 SIG_PRIVATE20 SIG_PRIVATE21 SIG_PRIVATE22 SIG_PRIVATE23 SIG_PRIVATE24 SIG_PRIVATE25 SIG_PRIVATE26 Private Section 2 Module
172
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Table 58. ATmega323 Boundary-Scan Order (Continued)
Bit Number 104 103 102 101 100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 76 75 74 Signal Name SIG_PRIVATE27 SIG_PRIVATE28 SIG_PRIVATE29 SIG_PRIVATE30 SIG_PRIVATE31 SIG_PRIVATE32 SIG_PRIVATE33 SIG_PRIVATE34 Private Section 2 (Cont.) SIG_PRIVATE35 SIG_PRIVATE36 SIG_PRIVATE37 SIG_PRIVATE38 SIG_PRIVATE39 SIG_PRIVATE40 SIG_PRIVATE41 SIG_PRIVATE42 PB0.Data PB0.Control PB0.PuLLup_Disable PB1.Data PB1.Control PB1.PuLLup_Disable PB2.Data PB2.Control PB2.PuLLup_Disable PB3.Data PB3.Control PB3.PuLLup_Disable PB4.Data PB4.Control PB4.PuLLup_Disable Port B Module
173
1457G-AVR-09/03
Table 58. ATmega323 Boundary-Scan Order (Continued)
Bit Number 73 72 71 70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 Signal Name PB5.Data PB5.Control PB5.PuLLup_Disable PB6.Data PB6.Control PB6.PuLLup_Disable PB7.Data PB7.Control PB7.PuLLup_Disable RSTT SIG_PRIVATE43 SIG_PRIVATE44 SIG_PRIVATE45 SIG_PRIVATE46 PD0.Data PD0.Control PD0.PuLLup_Disable PD1.Data PD1.Control PD1.PuLLup_Disable PD2.Data PD2.Control PD2.PuLLup_Disable PD3.Data PD3.Control PD3.PuLLup_Disable PD4.Data PD4.Control PD4.PuLLup_Disable Port D Observe-Only cells Port B Module
174
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Table 58. ATmega323 Boundary-Scan Order (Continued)
Bit Number 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 Signal Name PD5.Data PD5.Control PD5.PuLLup_Disable PD6.Data PD6.Control PD6.PuLLup_Disable PD7.Data PD7.Control PD7.PuLLup_Disable PC0.Data PC0.Control PC0.PuLLup_Disable PC1.Data PC1.Control PC1.PuLLup_Disable Port C PC6.Data PC6.Control PC6.PuLLup_Disable PC7.Data PC7.Control PC7.PuLLup_Disable PA7.Data PA7.Control PA7.PuLLup_Disable PA6.Data PA6.Control PA6.PuLLup_Disable Port A PA5.Data PA5.Control PA5.PuLLup_Disable PA4.Data PA4.Control PA4.PuLLup_Disable Port D Module
175
1457G-AVR-09/03
Table 58. ATmega323 Boundary-Scan Order (Continued)
Bit Number 11 10 9 8 7 6 5 4 3 2 1 0 Signal Name PA3.Data PA3.Control PA3.PuLLup_Disable PA2.Data PA2.Control PA2.PuLLup_Disable Port A PA1.Data PA1.Control PA1.PuLLup_Disable PA0.Data PA0.Control PA0.PuLLup_Disable Module
Boundary-Scan Description Language Files
Boundary-Scan Description Language (BSDL) files describe Boundary-Scan capable devices in a standard format used by automated test-generation software. The order and function of bits in the Boundary-Scan Data Register are included in this description. A BSDL file for ATmega323 is available.
176
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Memory Programming
Boot Loader Support
The ATmega323 provides a mechanism for downloading and uploading program code by the MCU itself. This feature allows flexible application software updates, controlled by the MCU using a Flash-resident Boot Loader program. This makes it possible to program the AVR in a target system without access to its SPI pins. The Boot Loader program can use any available data interface and associated protocol, such as USART serial bus interface, to input or output program code, and write (program) that code into the Flash memory, or read the code from the Flash memory. The ATmega323 Flash memory is organized in two main sections: * * The Application Flash section The Boot Loader Flash section
The Application Flash section and the Boot Loader Flash section have separate Boot Lock bits. Thus the user can select different levels of protection for the two sections. The Store Program memory (SPM) instruction can only be executed from the Boot Loader Flash section. The program Flash memory in ATmega323 is divided into 256 pages of 64 words each. The Boot Loader Flash section is located at the high address space of the Flash, and can be configured through the BOOTSZ Fuses as shown in Table 59. Table 59. Boot Size Configuration
BOOTSZ1 1 1 0 0 BOOTSZ0 1 0 1 0 Boot Size 256 words 512 words 1024 words 2048 words Pages 4 8 16 32 Application Flash Addresses $0000 - $3EFF $0000 - $3DFF $0000 - $3BFF $0000 - $37FF Boot Flash Addresses $3F00 $3FFF $3E00 $3FFF $3C00 $3FFF $3800 $3FFF Boot Reset Address $3F00 $3E00 $3C00 $3800
177
1457G-AVR-09/03
Figure 92. Memory Sections
Pages
Program Memory BOOTSZ = '11' $0000
Pages
Program Memory BOOTSZ = '10' $0000
252
Application Flash Section (16128 x 16)
248
Application Flash Section (15872 x 16)
4
Boot Flash Section (256 x 16)
$3EFF $3F00 $3FFF
8
Boot Flash Section (512 x 16)
$3DFF $3E00 $3FFF
Pages
Program Memory BOOTSZ = '01' $0000
Pages
Program Memory BOOTSZ = '00' $0000
240
Application Flash Section (15360 x 16)
224
Application Flash Section (14336 x 16)
$3BFF $3C00
16
$37FF $3800
32
Boot Flash Section (1024 x 16) $3FFF
Boot Flash Section (2048 x 16) $3FFF
178
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Entering the Boot Loader The SPM instruction can access the entire Flash, but can only be executed from the Boot Loader Flash section. If no Boot Loader capability is needed, the entire Flash is Program
available for application code. Entering the Boot Loader takes place by a jump or call from the application program. This may be initiated by some trigger such as a command received via USART or SPI interface, for example. Alternatively, the Boot Reset Fuse can be programmed so that the Reset Vector is pointing to the Boot Flash start address after a reset. In this case, the Boot Loader is started after a reset. After the application code is loaded, the program can start executing the application code. Note that the fuses cannot be changed by the MCU itself. This means that once the Boot Reset Fuse is programmed, the Reset Vector will always point to the Boot Loader Reset and the fuse can only be changed through the Serial or Parallel Programming interface. Table 60. Boot Reset Fuse
BOOTRST 0 1 Reset Address Reset Vector = Application Reset (address $0000) Reset Vector = Boot Loader Reset (see Table 59)
Capabilities of the Boot Loader
The program code within the Boot Loader section has the capability to read from and write into the entire Flash, including the Boot Loader Memory. This allows the user to update both the Application code and the Boot Loader code that handles the software update. The Boot Loader can thus even modify itself, and it can also erase itself from the code if the feature is not needed anymore. Programming of the Flash is executed one page at a time. The Flash page must be erased first for correct programming. The general Write Lock (Lock bit 2) does not control the programming of the Flash memory by SPM instruction. Similarly, the general Read/Write Lock (Lock bit 1) does not control reading nor writing by LPM/SPM, if it is attempted. The Program memory can only be updated page by page, not word by word. One page is 128 bytes (64 words). The Program memory will be modified by first performing page erase, then filling the temporary page buffer one word at a time using SPM, and then executing page write. If only part of the page needs to be changed, the other parts must be stored (for example in internal SRAM) before the erase, and then be rewritten. The temporary page buffer can be accessed in a random sequence. It is essential that the page address used in both the page erase and page write operation is addressing the same page. See "Assembly code example for a Boot Loader" on page 185 for an assembly code example.
Self-programming the Flash
Performing Page Erase by SPM
To execute Page Erase, set up the address in the Z-pointer, write "00011" to the five LSB in SPMCR and execute SPM within four clock cycles after writing SPMCR. The data in R1 and R0 is ignored. The page address must be written to Z14:Z7. Other bits in the Z-pointer will be ignored during this operation. It is recommended that the interrupts are disabled during the Page Erase operation. To write an instruction word, set up the address in the Z-pointer and data in R1:R0, write "00001" to the five LSB in SPMCR and execute SPM within four clock cycles after writing SPMCR. The content of Z6:Z1 is used to address the data in the temporary buffer. Z14:Z7 must point to the page that is supposed to be written.
Fill the Temporary Buffer (Page Load)
179
1457G-AVR-09/03
Perform a Page Write
To execute page write, set up the address in the Z-pointer, write "00101" to the five LSB in SPMCR and execute SPM within four clock cycles after writing SPMCR. The data in R1 and R0 is ignored. The page address must be written to Z14:Z7. During this operation, Z6:Z0 must be zero to ensure that the page is written correctly. It is recommended that the interrupts are disabled during the page write operation. Special care must be taken if the user allows the Boot Loader section to be updated by leaving Boot Lock bit 11 unprogrammed. An accidental write to the Boot Loader itself can corrupt the entire Boot Loader, and further software updates might be impossible. If it is not necessary to change the Boot Loader software itself, it is recommended to program the Boot Lock bit 11 to protect the Boot Loader software from any internal software changes. Though the CPU is halted during Page Write, Page Erase or Lock bit write, for future compatibility, the user software must poll for SPM complete by reading the SPMCR Register and loop until the SPMEN bit is cleared after a programming operation. See "Assembly code example for a Boot Loader" on page 185 for a code example. To ensure proper instruction pipelining after programming action (Page Erase, Page Write, or Lock bit write), the SPM instruction must be followed with the sequence (.dw $FFFF - NOP) as shown below:
spm .dw $FFFF nop
Consideration while Updating the Boot Loader Section
Wait for SPM Instruction to Complete
Instruction Word Read after Page Erase, Page Write, and Lock Bit Write
If not, the instruction following SPM might fail. It is not necessary to add this sequence when the SPM instruction only loads the temporary buffer. Avoid Reading the Application Section During Selfprogramming During Self-programming (either Page Erase or Page Write), the user software should not read the application section. The user software itself must prevent addressing this section during the Self-programming operations. This implies that interrupts must be disabled or moved to the Boot Loader section. Before addressing the application section after the programming is completed, for future compatibility, the user software must write"10001" to the five LSB in SPMCR and execute SPM within four clock cycles. Then the user software should verify that the ASB bit is cleared. See "Assembly code example for a Boot Loader" on page 185 for an example. Though the ASB and ASRE bits have no special function in this device, it is important for future code compatibility that they are treated as described above. ATmega323 has two separate sets of Boot Lock bits which can be set independently. This gives the user a unique flexibility to select different levels of protection. The user can select: * * * * To protect the entire Flash from a software update by the MCU. To only protect the Boot Loader Flash section from a software update by the MCU. To only protect application Flash section from a software update by the MCU. Allowing software update in the entire Flash.
Boot Loader Lock Bits
See Table 61 for further details. The Boot Lock bits can be set in software and in Serial or Parallel Programming mode, but they can only be cleared by a chip erase command.
180
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Table 61. Boot Lock Bit0 Protection Modes (Application Section)(1)
BLB0 Mode 1 2 3 BLB02 1 1 0 BLB01 1 0 0 Protection No restrictions for SPM or LPM accessing the Application section. SPM is not allowed to write to the Application section. SPM is not allowed to write to the Application section, and LPM executing from the Boot Loader section is not allowed to read from the Application section. If Interrupt Vectors are placed in the Boot Loader section, interrupts are disabled while executing from the Application section. LPM executing from the Boot Loader section is not allowed to read from the Application section. If Interrupt Vectors are placed in the Boot Loader section, interrupts are disabled while executing from the Application section.
4
0
1
Note:
1. "1" means unprogrammed, "0" means programmed
Table 62. Boot Lock Bit1 Protection Modes (Boot Loader Section)(1)
BLB1 mode 1 2 3 BLB12 1 1 0 BLB11 1 0 0 Protection No restrictions for SPM or LPM accessing the Boot Loader section. SPM is not allowed to write to the Boot Loader section. SPM is not allowed to write to the Boot Loader section, and LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interrupt Vectors are placed in the Application section, interrupts are disabled while executing from the Boot Loader section. LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interrupt Vectors are placed in the Application section, interrupts are disabled while executing from the Boot Loader section.
4
0
1
Note:
1. "1" means unprogrammed, "0" means programmed
Setting the Boot Loader Lock Bits by SPM
To set the Boot Loader Lock bits, write the desired data to R0, write "00001001" to SPMCR and execute SPM within four clock cycles after writing SPMCR. The only accessible Lock bits are the Boot Lock bits that may prevent the Application and Boot Loader section from any software update by the MCU.
Bit R0 7 1 6 1 5 BLB12 4 BLB11 3 BLB02 2 BLB01 1 1 0 1
If bits 5..2 in R0 are cleared (zero), the corresponding Boot Lock Bit will be programmed if an SPM instruction is executed within four cycles after BLBSET and SPMEN are set in SPMCR.
181
1457G-AVR-09/03
Reading the Fuse and Lock Bits from Software
It is possible to read both the Fuse and Lock bits from software. To read the Lock bits, load the Z-pointer with $0001 and set the BLBSET and SPMEN bits in SPMCR. When an LPM instruction is executed within five CPU cycles after the BLBSET and SPMEN bits are set in SPMCR, the value of the Lock bits will be loaded in the destination register. The BLBSET and SPMEN bits will auto-clear upon completion of reading the Lock bits or if no SPM, or LPM, instruction is executed within four, respectively five, CPU cycles. When BLBSET and SPMEN are cleared, LPM will work as described in "Constant Addressing Using the LPM and SPM Instructions" on page 16 and in the Instruction set Manual.
Bit Rd 7 - 6 - 5 BLB12 4 BLB11 3 BLB02 2 BLB01 1 LB2 0 LB1
The algorithm for reading the Fuse Low bits is similar to the one described above for reading the Lock bits. To read the Fuse Low bits, load the Z-pointer with $0000 and set the BLBSET and SPMEN bits in SPMCR. When an LPM instruction is executed within five cycles after the BLBSET and SPMEN bits are set in the SPMCR, the value of the Fuse Low bits will be loaded in the destination register as shown below.
Bit Rd 7 BODLEVEL 6 BODEN 5 - 4 - 3 CKSEL3 2 CKSEL2 1 CKSEL1 0 CKSEL0
Similarly, when reading the Fuse High bits, load $0003 in the Z-pointer. When an LPM instruction is executed within five cycles after the BLBSET and SPMEN bits are set in the SPMCR, the value of the Fuse High bits will be loaded in the destination register as shown below.
Bit Rd 7 OCDEN 6 JTAGEN 5 SPIEN 4 - 3 EESAVE 2 BOOTSZ1 1 BOOTSZ0 0 BOOTRST
Fuse and Lock bits that are programmed, will be read as zero. Fuse and Lock bits that are unprogrammed, will be read as one. In all cases, the read value of unused bit positions are undefined.
EEPROM Write Prevents Writing to SPMCR
Note that an EEPROM write operation will block all software programming to Flash. Reading the Fuses and Lock bits from software will also be prevented during the EEPROM write operation. It is recommended that the user checks the status bit (EEWE) in the EECR Register and verifies that the bit is cleared before writing to the SPMCR Register. If EEPROM writing is performed inside an interrupt routine, the user software should disable that interrupt before checking the EEWE status bit. The Z-pointer is used to address the SPM commands.
Bit ZH (R31) ZL (R30) 15 Z15 Z7 7 14 Z14 Z6 6 13 Z13 Z5 5 12 Z12 Z4 4 11 Z11 Z3 3 10 Z10 Z2 2 9 Z9 Z1 1 8 Z8 Z0 0
Addressing the Flash During Self-programming
Z15 Z14:Z7 Z6:Z1 Z0
always ignored page select, for page erase and page write word select, for filling temp buffer (must be zero during page write operation) should be zero for all SPM commands, byte select for the LPM instruction.
The only operation that does not use the Z-pointer is Setting the Boot Loader Lock bits. The content of the Z-pointer is ignored and will have no effect on the operation.
182
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Note that the page erase and page write operation is addressed independently. Therefore it is of major importance that the Boot Loader software addresses the same page in both the page erase and page write operation. The LPM instruction also uses the Z-pointer to store the address. Since this instruction addresses the Flash byte-by-byte, also the LSB (bit Z0) of the Z-pointer is used. See page 16 for a detailed description. Store Program Memory Control Register - SPMCR The Store Program memory Control Register contains the control bits needed to control the programming of the Flash from internal code execution.
Bit $37 ($57) Read/Write Initial Value 7 - R x 6 ASB R 0 5 - R 0 4 ASRE R/W 0 3 BLBSET R/W 0 2 PGWRT R/W 0 1 PGERS R/W 0 0 SPMEN R/W 0 SPMCR
* Bit 7 - Res: Reserved Bit This bit is a reserved bit in the ATmega323 and always reads as zero. This bit should be written to zero when writing SPMCR. * Bit 6 - ASB: Application Section Busy Before entering the Application section after a Boot Loader operation (Page Erase or Page Write) the user software must verify that this bit is cleared. In future devices, this bit will be set to "1" by page erase and page write. In ATmega323, this bit always reads as zero. * Bit 5 - Res: Reserved Bit This bit is a reserved bit in the ATmega323 and always reads as zero. This bit should be written to zero when writing SPMCR. * Bit 4 - ASRE: Application Section Read Enable Before re-entering the application section, the user software must set this bit together with the SPMEN bit and execute SPM within four clock cycles. * Bit 3 - BLBSET: Boot Lock Bit Set If this bit is set at the same time as SPMEN, the next SPM instruction within four clock cycles will set Boot Lock bits. Alternatively, an LPM instruction within five cycles will read either the Lock bits or the Fuse bits. The BLBSET bit will auto-clear upon completion of the SPM or LPM instruction, or if no SPM, or LPM, instruction is executed within four, respectively five, clock cycles. * Bit 2 - PGWRT: Page Write If this bit is set at the same time as SPMEN, the next SPM instruction within four clock cycles executes page write, with the data stored in the temporary buffer. The page address is taken from the high part of the Z-pointer. The data in R1 and R0 are ignored. The PGWRT bit will auto-clear upon completion of a page write, or if no SPM instruction is executed within four clock cycles. The CPU is halted during the entire page write operation.
183
1457G-AVR-09/03
* Bit 1 - PGERS: Page Erase If this bit is set at the same time as SPMEN, the next SPM instruction within four clock cycles executes page erase. The page address is taken from the high part of the Zpointer. The data in R1 and R0 are ignored. The PGERS bit will auto-clear upon completion of a page erase, or if no SPM instruction is executed within four clock cycles. The CPU is halted during the entire page erase operation. * Bit 0 - SPMEN: Store Program Memory Enable This bit enables the SPM instruction for the next four clock cycles. If set together with either ASRE, BLBSET, PGWRT, or PGERS, the following SPM instruction will have a special meaning, see description above. If only SPMEN is set, the following SPM instruction will store the value in R1:R0 in the temporary page buffer addressed by the Z-pointer. The LSB of the Z-pointer is ignored. The SPMEN bit will auto-clear upon completion of an SPM instruction, or if no SPM instruction is executed within four clock cycles. During page erase and page write, the SPMEN bit remains high until the operation is completed. Writing any other combination than "10001", "01001", "00101", or "00001" in the lower five bits will have no effect.
Preventing Flash Corruption
During periods of low VCC, the Flash can be corrupted because the supply voltage is too low for the CPU and the Flash to operate properly. These issues are the same as for board level systems using the Flash, and the same design solutions should be applied. A Flash corruption can be caused by two situations when the voltage is too low. First, a regular write sequence to the Flash requires a minimum voltage to operate correctly. Secondly, the CPU itself can execute instructions incorrectly, if the supply voltage for executing instructions is too low. Flash corruption can easily be avoided by following these design recommendations (one is sufficient): 1. Keep the AVR RESET active (low) during periods of insufficient power supply voltage. This can be done be enabling the internal Brown-Out Detector (BOD) if the operating voltage matches the detection level. If not, an external low VCC Reset Protection circuit can be used. If a reset occurs while a write operation is in progress, the write operation will be completed provided that the power supply voltage is sufficient. The total reset time must be longer than the Flash write time. This can be achieved by holding the External Reset, or by selecting a long reset timeout. 2. Keep the AVR core in Power-down sleep mode during periods of low VCC. This will prevent the CPU from attempting to decode and execute instructions, effectively protecting the Flash from unintentional writes.
184
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Assembly code example for a Boot Loader
;- the routine writes one page of data from RAM to Flash the first data : location in RAM is pointed to by the Y pointer (lowest address) the first ; data location in Flash is pointed to by the Z-pointer (lowest address) ; - error handling is not included - the routine must be placed inside the ; boot space. Only code inside boot loader section should be read during ; self-programming. ;- registers used: r0, r1, temp1, temp2, looplo, loophi, spmcrval storing and ; restoring of registers is not included in the routine ; register usage can be optimized at the expense of code size ;- It is assumed that the interrupts are disabled .equ PAGESIZEB = PAGESIZE*2 ;PAGESIZEB is page size in BYTES, not words .org SMALLBOOTSTART Write_page: ; page erase ldi spmcrval, (1<185
1457G-AVR-09/03
call Do_spm rjmp Return Do_spm: ; input: spmcrval determines SPM action ; check that no EEPROM write access is running Wait_ee: sbic EECR, EEWE rjmp Wait_ee ; SPM timed sequence out SPMCR, spmcrval spm .dw $FFFF nop ; check for SPM complete Wait_spm: in temp1, SPMCR sbrc temp1, SPMEN rjmp Wait_spm ret ; ensure proper pipelining ; of next instruction
Program and Data Memory Lock Bits
The ATmega323 provides six Lock bits which can be left unprogrammed ("1") or can be programmed ("0") to obtain the additional features listed in Table 63. The Lock bits can only be erased to "1" with the Chip Erase command. Table 63. Lock Bit Protection Modes
Memory Lock Bits LB mode 1 2 LB2 1 1 LB1 1 0 Protection Type No memory lock features enabled for parallel, serial, and JTAG programming. Further programming of the Flash and EEPROM is disabled in parallel, serial, and JTAG programming mode. The Fuse bits are locked in both serial and parallel programming mode.(1) Further programming and verification of the Flash and EEPROM is disabled in parallel, serial, and JTAG programming mode. The Fuse bits are locked in both serial and parallel programming mode.(1)
3
0
0
BLB0 mode 1 2 3
BLB02 1 1 0
BLB01 1 0 0 No restrictions for SPM or LPM accessing the Application section. SPM is not allowed to write to the Application section. SPM is not allowed to write to the Application section, and LPM executing from the Boot Loader section is not allowed to read from the Application section. If Interrupt Vectors are placed in the Boot Loader section, interrupts are disabled while executing from the Application section. LPM executing from the Boot Loader section is not allowed to read from the Application section. If Interrupt Vectors are placed in the Boot Loader section, interrupts are disabled while executing from the Application section.
4
0
1
BLB1 mode
BLB12
BLB11
186
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Table 63. Lock Bit Protection Modes
Memory Lock Bits LB mode 1 2 3 LB2 1 1 0 LB1 1 0 0 Protection Type No restrictions for SPM or LPM accessing the Boot Loader section. SPM is not allowed to write to the Boot Loader section. SPM is not allowed to write to the Boot Loader section, and LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interrupt Vectors are placed in the Application section, interrupts are disabled while executing from the Boot Loader section. LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interrupt Vectors are placed in the Application section, interrupts are disabled while executing from the Boot Loader section.
4
0
1
Note:
1. Program the Fuse bits before programming the Lock bits.
Fuse Bits
The ATmega323 has 13 Fuse bits, divided in two groups. The Fuse High bits are OCDEN, JTAGEN, SPIEN, EESAVE, BOOTSZ1..0, and BOOTRST, and the Fuse Low bits are BODLEVEL, BODEN, and CKSEL3..0. All Fuses are accessible in Parallel Programming mode and when programming via the JTAG interface. In Serial Programming mode, all but the SPIEN Fuse is accessible. * When the OCDEN Fuse is programmed, the On-chip debug system is enabled if the JTAGEN Fuse is programmed. If the JTAGEN Fuse is unprogrammed, the OCDEN Fuse has no visible effect.Never ship a product with the OCDEN Fuse programmed. Regardless of the setting of Lock bits and the JTAGEN Fuse, a programmed OCDEN Fuse enables some parts of the clock system be running in all sleep modes. This may increase the power consumption. Default value is unprogrammed ("1"). When the JTAGEN Fuse is programmed, the JTAG interface is enabled on port C pins PC5..2. Default value is programmed ("0"). If the JTAG interface is left unconnected, the JTAGEN fuse should if possible be disabled. This to avoid static current at the TDO pin in the JTAG interface. When the SPIEN Fuse is programmed ("0"), Serial Program and Data Downloading are enabled. Default value is programmed ("0"). The SPIEN Fuse is not accessible in SPI Serial Programming mode. When EESAVE is programmed, the EEPROM Memory is preserved through the Chip Erase cycle. Default value is unprogrammed ("1"). The EESAVE Fuse bit can not be programmed if any of the Lock bits are programmed. BOOTSZ1..0 select the size and start address of the Boot Flash section according to Table on page 177. Default value is "11" (both unprogrammed). When BOOTRST is programmed ("0"), the Reset Vector is set to the start address of the Boot Flash section, as selected by the BOOTSZ Fuses according to Table 59 on page 177. If the BOOTRST is unprogrammed ("1"), the Reset Vector is set to address $0000. Default value is unprogrammed ("1"). The BODLEVEL Fuse selects the Brown-out Detection Level and changes the Startup times, according to Table 5 on page 26 and Table 6 on page 27, respectively. Default value is unprogrammed ("1").
* * *
*
* *
*
187
1457G-AVR-09/03
*
When the BODEN Fuse is programmed ("0"), the Brown-out Detector is enabled. See "Reset and Interrupt Handling" on page 22. Default value is unprogrammed ("1"). CKSEL3..0 select the clock source and the start-up delay after reset, according to Table 1 on page 6 and Table 6 on page 27. Default value is "0010" (Internal RC Oscillator, slowly rising power).
*
The status of the Fuse bits is not affected by Chip Erase. Note that the Fuse bits are locked if Lock bit1 (LB1) is programmed. Program the Fuse bits before programming the Lock bits. Signature Bytes All Atmel microcontrollers have a 3-byte signature code which identifies the device. This code can be read in both serial and parallel mode. The three bytes reside in a separate address space. For the ATmega323 the signature bytes are: 1. $000: $1E (indicates manufactured by Atmel) 2. $001: $95 (indicates 32KB Flash memory) 3. $002: $01 (indicates ATmega323 device when $001 is $95) Calibration Byte The ATmega323 has a one byte calibration value for the internal RC Oscillator. This byte resides in the High Byte of address $000 in the signature address space. To make use of this byte, it should be read from this location and written into the normal Flash Program memory by the external programmer. At start-up, the user software must read this Flash location and write the value to the OSCCAL Register. This section describes how to parallel program and verify Flash Program memory, EEPROM Data memory + Program And Data memory Lock bits and Fuse bits in the ATmega323. Pulses are assumed to be at least 500ns unless otherwise noted. In this section, some pins of the ATmega323 are referenced by signal names describing their functionality during parallel programming, see Figure 93 and Table 64. Pins not described in the following table are referenced by pin names. The XA1/XA0 pins determine the action executed when the XTAL1 pin is given a positive pulse. The bit coding are shown in Table 65. When pulsing WR or OE, the command loaded determines the action executed. The Command is a byte where the different bits are assigned functions as shown in Table 66.
Parallel Programming
Signal Names
188
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Figure 93. Parallel Programming
ATmega323 +5V RDY/BSY OE WR BS1 XA0 XA1 PAGEL +12 V BS2 PD1 PD2
PB7 - PB0
VCC DATA
PD3 PD4 PD5 PD6 PD7 RESET PA0 XTAL1 GND
Table 64. Pin Name Mapping
Signal Name in Programming Mode RDY/BSY OE WR BS1 XA0 XA1 PAGEL BS2 DATA Pin Name PD1 PD2 PD3 PD4 PD5 PD6 PD7 PA0 PB7 - 0 I/O O I I I I I I I I/O Function 0: Device is Busy Programming, 1: Device is Ready for New Command Output Enable (Active Low) Write Pulse (Active Low) Byte Select 1 ("0" Selects Low Byte, "1" Selects High Byte) XTAL Action Bit 0 XTAL Action Bit 1 Program Memory Page Load Byte Select 2 ("0" Selects Low Byte, "1" Selects 2 nd High Byte) Bidirectional Data Bus (Output When OE is Low)
Table 65. XA1 and XA0 Coding
XA1 0 0 1 1 XA0 0 1 0 1 Action When XTAL1 is Pulsed Load Flash or EEPROM Address (High or Low Address Byte Determined by BS1) Load Data (High or Low Data Byte for Flash Determined by BS1) Load Command No Action, Idle
189
1457G-AVR-09/03
Table 66. Command Byte Bit Coding
Command Byte 1000 0000 0100 0000 0010 0000 0001 0000 0001 0001 0000 1000 0000 0100 0000 0010 0000 0011 Command Executed Chip Erase Write Fuse bits Write Lock bits Write Flash Write EEPROM Read Signature Bytes Read Fuse and Lock bits Read Flash Read EEPROM
Enter Programming Mode
The following algorithm puts the device in Parallel Programming mode: 1. Apply 4.5 - 5.5V between VCC and GND. 2. Set RESET and BS1 pins to "0" and wait at least 100 ns. 3. Apply 11.5 - 12.5V to RESET. Any activity on BS1 within 100 ns after +12V has been applied to RESET, will cause the device to fail entering programming mode.
Chip Erase
The Chip Erase command will erase the Flash and EEPROM memories and the Lock bits. The Lock bits are not reset until the Program memory has been completely erased. The Fuse bits are not changed. A Chip Erase must be performed before the Flash is reprogrammed. Load Command "Chip Erase" 1. Set XA1, XA0 to "10". This enables command loading. 2. Set BS1 to "0". 3. Set DATA to "1000 0000". This is the command for Chip Erase. 4. Give WR a negative pulse. This starts the Chip Erase. RDY/BSY goes low. 5. Wait until RDY/BSY goes high before loading a new command.
Programming the Flash
The Flash is organized as 256 pages of 128 bytes each. When programming the Flash, the program data is latched into a page buffer. This allows one page of program data to be programmed simultaneously. The following procedure describes how to program the entire Flash memory: A. Load Command "Write Flash" 1. Set XA1, XA0 to "10". This enables command loading. 2. Set BS1 to "0". 3. Set DATA to "0001 0000". This is the command for Write Flash. 4. Give XTAL1 a positive pulse. This loads the command. B. Load Address Low Byte 1. Set XA1, XA0 to "00". This enables address loading. 2. Set BS1 to "0". This selects low address. 3. Set DATA = Address Low Byte ($00 - $FF). 4. Give XTAL1 a positive pulse. This loads the address Low Byte.
190
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
C. Load Data Low Byte 1. Set XA1, XA0 to "01". This enables data loading. 2. Set DATA = Data Low Byte ($00 - $FF). 3. Give XTAL1 a positive pulse. This loads the data byte. D. Load Data High Byte 1. Set BS1 to "1". This selects high data byte. 2. Set XA1, XA0 to "01". This enables data loading. 3. Set DATA = Data High Byte ($00 - $FF). 4. Give XTAL1 a positive pulse. This loads the data byte. E. Latch Data High and Low Byte 1. Set BS1 to "1". 2. Give PAGEL a positive pulse. See Figure 94 for signal waveforms. F. Repeat B through F 64 Times to Fill the Page Buffer. To address a page in the Flash, 8 bits are needed (256 pages). The 6 most significant bits are read from address High Byte as described in section "H" below. The two least significant page address bits however, are the two most significant bits (bit7 and bit6) of the latest loaded address Low Byte as described in section "B". G. Load Address High Byte 1. 1. Set XA1, XA0 to "00". This enables address loading. 2. Set BS1 to "1". This selects high address. 3. Set DATA = Address High Byte ($00 - $3F). 4. Give XTAL1 a positive pulse. This loads the address High Byte. H. Program Page 1. Give WR a negative pulse. This starts programming of the entire page of data. RDY/BSYgoes low. 2. Wait until RDY/BSY goes high. (See Figure 95 for signal waveforms) I. End Page Programming 1. 1. Set XA1, XA0 to "10". This enables command loading. 2. Set DATA to "0000 0000". This is the command for No Operation. 3. Give XTAL1 a positive pulse. This loads the command, and the internal write signals are reset. J. Repeat A through I 256 Times or Until All Data Has Been Programmed.
191
1457G-AVR-09/03
Figure 94. Programming the Flash Waveforms
DATA
$10
ADDR. LOW
ADDR. HIGH
DATA LOW
XA1 XA2 BS1 XTAL1 WR RDY/BSY RESET +12V OE BS2 PAGEL
Figure 95. Programming the Flash Waveforms (continued)
DATA
DA TA HIGH
XA1 XA0 BS1 XTAL1 WR RDY/BSY
RESET OE PAGEL BS2
+12V
Programming the EEPROM
The programming algorithm for the EEPROM Data memory is as follows (refer to "Programming the Flash" on page 190 for details on Command, Address and Data loading): 1. A: Load Command "0001 0001". 2. H: Load Address High Byte ($00 - $03) 3. B: Load Address Low Byte ($00 - $FF) 4. C: Load Data Low Byte ($00 - $FF) K: Write Data Low Byte 1. Set BS1 to "0". This selects low data. 2. Give WR a negative pulse. This starts programming of the data byte. RDY/BSY goes low.
192
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
3. Wait until to RDY/BSY goes high before programming the next byte. (See Figure 96 for signal waveforms) The loaded command and address are retained in the device during programming. For efficient programming, the following should be considered. * * * The command needs only be loaded once when writing or reading multiple memory locations. Address High Byte needs only be loaded before programming a new 256 byte window in the EEPROM. Skip writing the data value $FF, that is the contents of the entire EEPROM after a Chip Erase.
These considerations also applies to Flash, EEPROM and Signature bytes reading. Figure 96. Programming the EEPROM Waveforms
DATA
$11 ADDR. HIGH ADDR. LOW DA TA LOW
XA1 XA2 BS1 XTAL1 WR RDY/BSY RESET +12V OE BS2 PAGEL
Reading the Flash
The algorithm for reading the Flash memory is as follows (refer to "Programming the Flash" on page 190 for details on Command and Address loading): 1. A: Load Command "0000 0010". 2. H: Load Address High Byte ($00 - $3F) 3. B: Load Address Low Byte ($00 - $FF) 4. Set OE to "0", and BS1 to "0". The Flash word Low Byte can now be read at DATA. 5. Set BS to "1". The Flash word High Byte can now be read at DATA. 6. Set OE to "1".
Reading the EEPROM
The algorithm for reading the EEPROM Memory is as follows (refer to "Programming the Flash" on page 190 for details on Command and Address loading): 1. A: Load Command "0000 0011". 2. H: Load Address High Byte ($00 - $03) 3. B: Load Address ($00 - $FF) 4. Set OE to "0", and BS1 to "0". The EEPROM Data byte can now be read at DATA.
193
1457G-AVR-09/03
5. Set OE to "1". Programming the Fuse Low Bits The algorithm for programming the Fuse Low bits is as follows (refer to "Programming the Flash" on page 190 for details on Command and Data loading): 1. A: Load Command "0100 0000". 2. C: Load Data Low Byte. Bit n = "0" programs and bit n = "1" erases the Fuse bit. Bit 7 = BODLEVEL Fuse bit Bit 6 = BODEN Fuse bit Bit 3..0 = CKSEL3..0 Fuse bits Bit 5,4 = "1". This bit is reserved and should be left unprogrammed ("1"). 3. Give WR a negative pulse and wait for RDY/BSY to go high. Programming the Fuse High Bits The algorithm for programming the Fuse high bits is as follows (refer to "Programming the Flash" on page 190 for details on Command and Data loading): 1. A: Load Command "0100 0000". 2. C: Load Data Low Byte. Bit n = "0" programs and bit n = "1" erases the Fuse bit. Bit 7 = OCDEN Fuse bit Bit 6 = JTAGEN Fuse bit Bit 5 = SPIEN Fuse bit Bit 3 = EESAVE Fuse bit Bit 2..1 = BOOTSZ1..0 Fuse bits Bit 0 = BOOTRST Fuse bit Bit 7,6,4 = "1". These bits are reserved and should be left unprogrammed ("1"). 3. Set BS1 to "1". This selects high data byte. 4. Give WR a negative pulse and wait for RDY/BSY to go high. 5. Set BS1 to "0". This selects low data byte. Programming the Lock Bits The algorithm for programming the Lock bits is as follows (refer to "Programming the Flash" on page 190 for details on Command and Data loading): 1. A: Load Command "0010 0000". 2. C: Load Data Low Byte. Bit n = "0" programs the Lock bit. Bit 5 = Boot Lock bit12 Bit 4 = Boot Lock bit11 Bit 3 = Boot Lock bit02 Bit 2 = Boot Lock bit01 Bit 1 = Lock bit2 Bit 0 = Lock bit1 Bit 7..6 = "1". These bits are reserved and should be left unprogrammed ("1"). 3. L: Write Data Low Byte. The Lock bits can only be cleared by executing Chip Erase. Reading the Fuse and Lock Bits The algorithm for reading the Fuse and Lock bits is as follows (refer to "Programming the Flash" on page 190 for details on Command loading): 1. A: Load Command "0000 0100". 2. Set OE to "0", BS2 to "0" and BS1 to "0". The status of the Fuse Low bits can now be read at DATA ("0" means programmed). Bit 7 = BODLEVEL Fuse bit Bit 6 = BODEN Fuse bit Bit 3..0 = CKSEL3..0 Fuse bits
194
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
3. Set OE to "0", BS2 to "1" and BS1 to "1". The status of the Fuse High bits can now be read at DATA ("0" means programmed). Bit 7 = OCDEN Fuse bit Bit 6 = JTAGEN Fuse bit Bit 5 = SPIEN Fuse bit Bit 3 = EESAVE Fuse bit Bit 2..1 = BOOTSZ1..0 Fuse bits Bit 0 = BOOTRST Fuse bit 4. Set OE to "0", BS2 to "0" and BS1 to "1". The status of the Lock bits can now be read at DATA ("0" means programmed). Bit 5 = Boot Lock bit12 Bit 4 = Boot Lock bit11 Bit 3 = Boot Lock bit02 Bit 2 = Boot Lock bit01 Bit 1 = Lock bit2 Bit 0 = Lock bit1 5. Set OE to "1". Reading the Signature Bytes The algorithm for reading the Signature bytes is as follows (refer to Programming the Flash for details on Command and Address loading): 1. A: Load Command "0000 1000". 2. C: Load Address Low Byte ($00 - $02). 3. Set OE to "0", and BS1 to "0". The selected Signature byte can now be read at DATA. 4. Set OE to "1". Reading the Calibration Byte The algorithm for reading the Calibration byte is as follows (refer to Programming the Flash for details on Command and Address loading): 1. A: Load Command "0000 1000". 2. C: Load Address Low Byte, $00. 3. Set OE to "0", and BS1 to "1". The Calibration byte can now be read at DATA. 4. Set OE to "1". Parallel Programming Characteristics Figure 97. Parallel Programming Timing
tXLWL XTAL1 tDVXH Data & Contol (DATA, XA0/1, BS1, BS2) tBVPH PAGEL WR RDY/BSY tWLRH tOLDV tPHPL tPLWL
WLRL
tXHXL tXLDX
tPLBX t BVWL tWLWH
tRHBX
DATA
195
1457G-AVR-09/03
Read
OE
tXLOL
tOHDZ
Write
Table 67. Parallel Programming Characteristics, TA = 25C 10%, VCC = 5 V 10%
Symbol VPP IPP tDVXH tXHXL tXLDX tXLWL tBVPH tPHPL tPLBX tPLWL tBVWL tRHBX tWLWH tWLRL tWLRH (1) tWLRH_CE
(2) (3)
Parameter Programming Enable Voltage Programming Enable Current Data and Control Valid before XTAL1 High XTAL1 Pulse Width High Data and Control Hold after XTAL1 Low XTAL1 Low to WR Low BS1 Valid before PAGEL High PAGEL Pulse Width High BS1 Hold after PAGEL Low PAGEL Low to WR Low BS1 Valid to WR Low BS1 Hold after RDY/BSY High WR Pulse Width Low WR Low to RDY/BSY Low WR Low to RDY/BSY High(1) WR Low to RDY/BSY High for Chip Erase
(2) (3)
Min 11.5
Typ
Max 12.5 250
Units V A ns ns ns ns ns ns ns ns ns ns ns
67 67 67 67 67 67 67 67 67 67 67 0 1 16 8 67 20 20 1.5 23 12 2.5 1.9 30 15
s ms ms ms ns ns ns
tWLRH_FLASH tXLOL tOLDV tOHDZ Notes: 1. 2. 3.
WR Low to RDY/BSY High for Write Flash XTAL1 Low to OE Low OE Low to DATA Valid OE High to DATA Tri-stated
tWLRH is valid for the Write EEPROM, Write Fuse bits and Write Lock bits commands. tWLRH_CE is valid for the Chip Erase command. tWLRH_FLASH is valid for the Write Flash command.
196
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Serial Downloading
Both the Flash and EEPROM Memory arrays can be programmed using the serial SPI bus while RESET is pulled to GND. The serial interface consists of pins SCK, MOSI (input) and MISO (output). After RESET is set low, the Programming Enable instruction needs to be executed first before program/erase operations can be executed. Figure 98. Serial Programming and Verify
ATmega323 2.7 - 5.5V VCC
MOSI MISO SCK
PB5 PB6 PB7
RESET
GND
When programming the EEPROM, an auto-erase cycle is built into the self-timed programming operation (in the serial mode ONLY) and there is no need to first execute the Chip Erase instruction. The Chip Erase operation turns the content of every memory location in both the Program and EEPROM arrays into $FF. The Program and EEPROM Memory arrays have separate address spaces: $0000 to $3FFF for Program memory and $0000 to $03FF for EEPROM Memory. The device can be clocked by any clock option during Low Voltage Serial Programming. The minimum low and high periods for the serial clock (SCK) input are defined as follows: Low: > 2 CPU clock cycles High: > 2 CPU clock cycles Serial Programming Algorithm When writing serial data to the ATmega323, data is clocked on the rising edge of SCK. When reading data from the ATmega323, data is clocked on the falling edge of SCK. See Figure 99, Figure 100, and Table 70 for timing details. To program and verify the ATmega323 in the Serial Programming mode, the following sequence is recommended (See four byte instruction formats in Table 69): 1. Power-up sequence: Apply power between V CC and GND while RESET and SCK are set to "0". The RESET and SCK are set to "0". In accordance with the setting of CKSEL Fuses, apply a crystal/resonator, external clock or RC network, or let the device run on the internal RC Oscillator. In some systems, the programmer can not guarantee that SCK is held low during Power-up. In this case, RESET must be given a positive pulse of at least two XTAL1 cycles duration after SCK has been set to "0". 2. Wait for at least 20 ms and enable Serial Programming by sending the Programming Enable serial instruction to pin MOSI/PB5.
197
1457G-AVR-09/03
3. The Serial Programming instructions will not work if the communication is out of synchronization. When in sync. the second byte ($53), will echo back when issuing the third byte of the Programming Enable instruction. Whether the echo is correct or not, all four bytes of the instruction must be transmitted. If the $53 did not echo back, give SCK a positive pulse and issue a new Programming Enable command. If the $53 is not seen within 32 attempts, there is no functional device connected. 4. If a chip erase is performed (must be done to erase the Flash), wait 2*tWD_FLASH after the instruction, give RESET a positive pulse, and start over from Step 2. See Table 68 for the tWD_FLASH figure. 5. The Flash is programmed one page at a time. The memory page is loaded one byte at a time by supplying the 6 LSB of the address and data together with the Load Program memory Page instruction. The Program memory Page is stored by loading the Write Program memory Page instruction with the 8 MSB of the address. If polling is not used, the user must wait at least tWD_FLASH before issuing the next page. (Please refer to Table 68). Accessing the Serial Programming interface before the Flash write operation completes can result in incorrect programming. 6. The EEPROM array is programmed one byte at a time by supplying the address and data together with the appropriate Write instruction. An EEPROM Memory location is first automatically erased before new data is written. If polling is not used, the user must wait at least tWD_EEPROM before issuing the next byte. (Please refer to Table 68). In a chip erased device, no $FFs in the data file(s) need to be programmed. 7. Any memory location can be verified by using the Read instruction which returns the content at the selected address at serial output MISO/PB6. 8. At the end of the programming session, RESET can be set high to commence normal operation. 9. Power-off sequence (if needed): Set XTAL1 to "0" (if a crystal is not used). Set RESET to "1". Turn VCC power off Data Polling Flash When a page is being programmed into the Flash, reading an address location within the page being programmed will give the value $FF. At the time the device is ready for a new page, the programmed value will read correctly. This is used to determine when the next page can be written. Note that the entire page is written simultaneously and any address within the page can be used for polling. Data polling of the Flash will not work for the value $FF, so when programming this value, the user will have to wait for at least tWD_FLASH before programming the next page. As a Chip Erased device contains $FF in all locations, programming of addresses that are meant to contain $FF, can be skipped. See Table 68 tWD_FLASH. When a new byte has been written and is being programmed into EEPROM, reading the address location being programmed will give the value $FF. At the time the device is ready for a new byte, the programmed value will read correctly. This is used to determine when the next byte can be written. This will not work for the value $FF, but the user should have the following in mind: As a Chip Erased device contains $FF in all locations, programming of addresses that are meant to contain $FF, can be skipped. This does not apply if the EEPROM is re-programmed without Chip Erasing the device. In this case, data polling cannot be used for the value $FF, and the user will have to wait at least tWD_EEPROM before programming the next byte. See Table 68 for tWD_EEPROM.
Data Polling EEPROM
198
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Programming Times for Nonvolatile Memory The internal RC Oscillator is used to control programming time when programming or erasing Flash, EEPORM, Fuses and Lock bits. During Parallel or Serial Programming, the device is in reset, and this Oscillator runs at its initial, uncalibrated frequency, which may vary from 0.5 MHz to 1.0 MHz. In software it is possible to calibrate this Oscillator to 1.0 MHz (see "Calibrated Internal RC Oscillator" on page 41). Consequently, programming times will be shorter and more accurate when programming or erasing non-volatile memory from software, using SPM or the EEPROM interface. See Table 68 for a summary of programming times. Table 68. Maximum Programming Times for Non-volatile Memory
Number of RC Oscillator Cycles 16K 8K 2K 1K Parallel/Serial Programming 2.7V 32 ms 16 ms 4 ms 2 ms 5.0V 30 ms 15 ms 3.8 ms 1.9 ms Selfprogramming
(1)
Operation Chip Erase Flash Write EEPROM Write(2) Fuse/Lock bit write Notes:
Symbol tWD_CE tWD_FLASH tWD_EEPROM tWD_FUSE
17 ms 8.5 ms 2.2 ms 1.1 ms
1. Includes variation over voltage and temperature after RC Oscillator has been calibrated to 1.0 MHz 2. Parallel EEPROM programming takes 1K cycles
Figure 99. Serial Programming Waveforms
SERIAL DATA INPUT PB5 (MOSI) SERIAL DATA OUTPUT PB6 (MISO) SERIAL CLOCK INPUT PB7(SCK)
SAMPLE
MSB
LSB
MSB
LSB
199
1457G-AVR-09/03
.
Table 69. Serial Programming Instruction Set
Instruction Format Instruction Programming Enable Chip Erase Read Program Memory Byte 1 1010 1100 1010 1100 0010 H000 Byte 2 0101 0011 100x xxxx xxaa aaaa Byte 3 xxxx xxxx xxxx xxxx bbbb bbbb Byte4 xxxx xxxx xxxx xxxx oooo oooo Operation Enable Serial Programming after RESET goes low. Chip Erase EEPROM and Flash. Read H (high or low) data o from Program memory at word address a:b. Write H (high or low) data i to Program memory page at word address b. Write Program memory Page at address a:b. Read data o from EEPROM Memory at address a:b. Write data i to EEPROM Memory at address a:b. Read Lock bits. "0" = programmed, "1" = unprogrammed. Write Lock bits. Set bits 6 - 1 = "0" to program Lock bits. Read Signature Byte o at address b. Set bits C - A, 9 - 7 = "0" to program, "1" to unprogram Set bits F - D = "0" to program, "1" to unprogram Read Fuse bits. "0" = programmed, "1" = unprogrammed Read Fuse high bits. "0" = programmed, "1" = unprogrammed Read Signature Byte o at address b.
Load Program Memory Page Write Program Memory Page Read EEPROM Memory Write EEPROM Memory Read Lock Bits Write Lock Bits Read Signature Byte Write Fuse Bits Write Fuse High Bits Read Fuse Bits Read Fuse High Bits Read Calibration Byte Note:
0100 H000
xxxx xxxx
xxbb bbbb
iiii iiii
0100 1100 1010 0000 1100 0000 0101 1000 1010 1100 0011 0000 1010 1100 1010 1100 0101 0000 0101 1000 0011 1000
xxaa aaaa xxxx xxaa xxxx xxaa 0000 0000 111x xxxx xxxx xxxx 1010 0000 1010 1000 0000 0000 0000 1000 xxxx xxxx
bbxx xxxx bbbb bbbb bbbb bbbb xxxx xxxx xxxx xxxx xxxx xxbb xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx 0000 0000
xxxx xxxx oooo oooo iiii iiii xx65 4321 1165 4321 oooo oooo CB11 A987 IH11 GFED CBxx A987 IHxx GFED oooo oooo
a = address high bits; b = address low bits; H = 0 - Low Byte, 1 - High Byte; o = data out; i = data in; x = don't care; 1 = lock bit 1; 2 = lock bit 2; 3 = Boot Lock Bit01; 4 = Boot Lock Bit02; 5 = Boot Lock Bit11; 6 = Boot Lock Bit12; 7 = CKSEL0 Fuse; 8 = CKSEL1 Fuse; 9 = CKSEL2 Fuse; A = CKSEL3 Fuse; B = BODEN Fuse; C = BODLEVEL Fuse; D = BOOTRST Fuse; E = BOOTSZ0 Fuse; F = BOOTSZ1 Fuse; G = EESAVE Fuse; H = JTAGEN Fuse; and I = OCDEN Fuse
200
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Serial Programming Characteristics Figure 100. Serial Programming Timing
MOSI tOVSH SCK MISO tSLIV
Table 70. Serial Programming Characteristics TA = -40C to 85C, VCC = 2.7V - 5.5V (Unless otherwise noted)
Symbol 1/tCLCL tCLCL 1/tCLCL tCLCL tSHSL tSLSH tOVSH tSHOX tSLIV Parameter Oscillator Frequency (VCC = 2.7 - 5.5 V) Oscillator Period (VCC = 2.7 - 5.5 V) Oscillator Frequency (VCC = 4.0 - 5.5 V) Oscillator Period (VCC = 4.0 - 5.5 V) SCK Pulse Width High SCK Pulse Width Low MOSI Setup to SCK High MOSI Hold after SCK High SCK Low to MISO Valid Min 0 250 0 125 2 tCLCL 2 tCLCL tCLCL 2 tCLCL 10 16 32 8 Typ Max 4 Units MHz ns MHz ns ns ns ns ns ns
tSHOX tSHSL
tSLSH
201
1457G-AVR-09/03
Programming via the JTAG Interface
Programming through the JTAG Interface requires control of the four JTAG specific pins: TCK, TMS, TDI, and TDO. Control of the reset and clock pins is not required. To be able to use the JTAG Interface, the JTAGEN Fuse must be programmed. The device is default shipped with the fuse programmed. In addition, the JTD bit in MCUCSR must be cleared. Alternatively, if the JTD bit is set, the External Reset can be forced low. Then, the JTD bit will be cleared after two chip clocks, and the JTAG pins are available for programming. This provides a means of using the JTAG pins as normal port pins in running mode while still allowing In-System Programming via the JTAG interface. Note that this technique can not be used when using the JTAG pins for Boundary-Scan or On-chip Debug. In these cases the JTAG pins must be dedicated for this purpose. As a definition in this datasheet, the LSB is shifted in and out first of all Shift Registers.
Programming specific JTAG instructions
The Instruction Register is four bit wide, supporting up to 16 instructions. The JTAG instructions useful for Programming are listed below. The OPCODE for each instruction is shown behind the instruction name in hex format. The text describes which Data Register is selected as path between TDI and TDO for each instruction. The Run-Test/Idle state of the TAP controller is used to generate internal clocks. It can also be used as an idle state between JTAG sequences.
AVR_RESET ($C)
The AVR specific public JTAG instruction for setting the AVR device in the Reset mode or taking the device out from the Reset mode. The TAP controller is not reset by this instruction. The one bit Reset Register is selected as Data Register. Note that the reset will be active as long as there is a logic 'one' in the Reset Chain. The output from this chain is not latched. The active states are: * Shift-DR: The Reset Register is shifted by the TCK input.
PROG_ENABLE ($4)
The AVR specific public JTAG instruction for enabling programming via the JTAG port. The 16 bit Programming Enable Register is selected as Data Register. The active states are the following: * * Shift-DR: The programming enable signature is shifted into the Data Register. Update-DR: The programming enable signature is compared to the correct value, and programming mode is entered if the signature is valid.
PROG_COMMANDS ($5)
The AVR specific public JTAG instruction for entering programming commands via the JTAG port. The 15-bit Programming Command Register is selected as Data Register. The active states are the following: * * * * Capture-DR: The result of the previous command is loaded into the Data Register. Shift-DR: The Data Register is shifted by the TCK input, shifting out the result of the previous command and shifting in the new command. Update-DR: The programming command is applied to the Flash inputs Run-Test/Idle: One clock cycle is generated, executing the applied command (not always required, see Table 71 below).
PROG_PAGELOAD ($6)
The AVR specific public JTAG instruction to directly load the Flash data page via the JTAG port. The 1024 bit Virtual Flash Page Load Register is selected as Data Register. This is a virtual scan chain with length equal to the number of bits in one Flash page. Internally the Shift Register is 8-bit. Unlike most JTAG instructions, the Update-DR state
202
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
is not used to transfer data from the Shift Register. The data are automatically transferred to the Flash page buffer byte-by-byte in the Shift-DR state by an internal state machine. This is the only active state: * Shift-DR: Flash page data are shifted in from TDI by the TCK input, and automatically loaded into the Flash page one byte at a time.
PROG_PAGEREAD ($7)
The AVR specific public JTAG instruction to read one full Flash data page via the JTAG port. The 1,032 bit Virtual Flash Page Read Register is selected as Data Register. This is a virtual scan chain with length equal to the number of bits in one Flash page plus eight. Internally the Shift Register is 8-bit. Unlike most JTAG instructions, the CaptureDR state is not used to transfer data to the Shift Register. The data are automatically transferred from the Flash page buffer byte-by-byte in the Shift-DR state by an internal state machine. This is the only active state: * Shift-DR: Flash data are automatically read one byte at a time and shifted out on TDO by the TCK input. The TDI input is ignored.
Data Registers
The Data Registers are selected by the JTAG Instruction Registers described in section "Programming specific JTAG instructions" on page 202. The Data Registers relevant for programming operations are: * * * * * Reset Register Programming Enable Register Programming Command Register Virtual Flash Page Load Register Virtual Flash Page Read Register
Reset Register
The Reset Register is a Test Data Register used to reset the part during programming. It is required to reset the part before entering Programming mode. A high value in the Reset Register corresponds to pulling the external Reset low. The part is reset as long as there is a high value present in the Reset Register. Depending on the Fuse settings for the clock options, the part will remain reset for a Reset TimeOut Period (refer to Table 6 on page 27) after releasing the Reset Register. The output from this Data Register is not latched, so the reset will take place immediately, as shown in Figure 93 on page 189.
Programming Enable Register
The Programming Enable Register is a 16-bit register. The contents of this register is compared to the programming enable signature, binary code 1010_0011_0111_0000. When the contents of the register is equal to the programming enable signature, programming via the JTAG port is enabled. The register is reset to 0 on Power-on Reset, and should always be reset when leaving Programming mode.
203
1457G-AVR-09/03
Figure 101. Programming Enable Register
TDI
D A T A
$A370
=
D
Q
Programming enable
ClockDR & PROG_ENABLE
TDO
Programming Command Register
The Programming Command Register is a 15-bit register. This register is used to serially shift in programming commands, and to serially shift out the result of the previous command, if any. The JTAG Programming Instruction Set is shown in Table 71. The state sequence when shifting in the programming commands is illustrated in Figure 102. Figure 102. Programming Command Register
TDI
S T R O B E S
A D D R E S S / D A T A
Flash EEPROM Fuses Lock Bits
TDO
204
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Table 71. JTAG Programming Instruction Set
Instruction 1a. Chip erase 1b. Poll for chip erase complete 2a. Enter Flash Write 2b. Load Address High Byte 2c. Load Address Low Byte 2d. Load Data Low Byte 2e. Load Data High Byte 2f. Latch Data TDI sequence 0100011_10000000 0110001_10000000 0110011_10000000 0110011_10000000 0100011_00010000 0000111_00aaaaaa 0000011_bbbbbbbb 0010011_iiiiiiii 0010111_iiiiiiii 0110111_00000000 1110111_00000000 0110111_00000000 0110111_00000000 0110101_00000000 0110111_00000000 0110111_00000000 0100011_00000010 0000111_00aaaaaa 0000011_bbbbbbbb 0110010_00000000 0110110_00000000 0110111_00000000 0100011_00010001 0000111_000000aa 0000011_bbbbbbbb 0010011_iiiiiiii 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 0100011_00000011 0000111_000000aa 0000011_bbbbbbbb 0110011_bbbbbbbb 0110010_00000000 0110011_00000000 0100011_01000000 0010011_IH11GFED TDO sequence xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (3) (1) (2) Low Byte High Byte (1) (2) Notes
2g. Write Page 2h. Poll for Page Write complete 3a. Enter Flash Read 3b. Load Address High Byte 3c. Load Address Low Byte 3d. Read Data Low and High Byte 4a. Enter EEPROM Write 4b. Load Address High Byte 4c. Load Address Low Byte 4d. Load Data Byte 4e. Write EEPROM byte 4f. Poll for Byte Write complete 5a. Enter EEPROM Read 5b. Load Address High Byte 5c. Load Address Low Byte 5d. Read Data Byte 6a. Enter Fuse Write 6b. Load Data High Byte
(1) (2)
205
1457G-AVR-09/03
Table 71. JTAG Programming Instruction Set (Continued)
Instruction 6c. Write Fuse High Byte 6d. Poll for Fuse Write complete 6e. Load Data Low Byte 6f. Write Fuse Low Byte 6g. Poll for Fuse Write complete 7a. Enter Lock Bit Write 7b. Load Data Byte 7c. Write Lock Bits 7d. Poll for Lock Bit Write complete 8a. Enter Fuse/Lock Bit Read 8b. Read Fuse High Byte 8c. Read Fuse Low Byte 8d. Read Lock Bits TDI sequence 0110111_00000000 0110101_00000000 0110111_00000000 0110111_00000000 0010011_CB11A987 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 0100011_00100000 0010011_11654321 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 0100011_00000100 0111110_00000000 0111111_00000000 0110010_00000000 0110011_00000000 0110110_00000000 0110111_00000000 0111110_00000000 0110010_00000000 0110110_00000000 0110111_00000000 0100011_00001000 0000011_bbbbbbbb 0110010_00000000 0110011_00000000 0100011_00001000 0000011_bbbbbbbb 0110110_00000000 0110111_00000000 0100011_00000000 0110011_00000000 TDO sequence xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxox_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_IHxxGFED xxxxxxx_xxxxxxxx xxxxxxx_CBxxA987 xxxxxxx_xxxxxxxx xxxxxxx_xx654321 xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_oooooooo xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_oooooooo xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (5) (5) Fuse High Byte Fuse Low Byte Lock bits (4) (1) (2) Notes (1) (2) (3) (1) (2)
8e. Read Fuses and Lock Bits
9a. Enter Signature Byte Read 9b. Load Address Byte 9c. Read Signature Byte 10a. Enter Calibration Byte Read 10b. Load Address Byte 10c. Read Calibration Byte 11a. Load No Operation Command Notes:
1. This command sequence is not required if the seven MSB are correctly set by the previous command sequence (which is normally the case). 2. Repeat until o = "1" 3. Set bits to "0" to program the corresponding fuse, "1" to unprogram the fuse.
206
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
4. Set bits to "0" to program the corresponding lock bit, "1" to leave the lock bit unchanged. 5. "0" = programmed, "1" = unprogrammed. 6. a = address High Byte; b = address Low Byte; i = data in; o = data out; 1 = lock bit 1; 2 = lock bit 2; 3 = Boot Lock Bit01; 4 = Boot Lock Bit02; 5 = Boot Lock Bit11; 6 = Boot Lock Bit12; 7 = CKSEL0 Fuse; 8 = CKSEL1 Fuse; 9 = CKSEL2 Fuse; A = CKSEL3 Fuse; B = BODEN Fuse; C = BODLEVEL Fuse; D = BOOTRST Fuse; E = BOOTSZ0 Fuse; F = BOOTSZ1 Fuse; G = EESAVE Fuse; H = JTAGEN Fuse; I = OCDEN Fuse
Figure 103. State Machine Sequence for Changing / Reading the Data Word
1 Test-Logic-Reset 0 0 Run-Test/Idle 1 Select-DR Scan 0 1 Capture-DR 0 Shift-DR 1 Exit1-DR 0 Pause-DR 1 0 Exit2-DR 1 Update-DR 1 0 0 0 1 0 1 1 Select-IR Scan 0 Capture-IR 0 Shift-IR 1 Exit1-IR 0 Pause-IR 1 Exit2-IR 1 Update-IR 1 0 0 1 0 1
207
1457G-AVR-09/03
Virtual Flash Page Load Register
The Virtual Flash Page Load Register is a virtual scan chain with length equal to the number of bits in one Flash page, 1,024. Internally the Shift Register is 8-bit, and the data are automatically transferred to the Flash page buffer byte-by-byte. Shift in all instruction words in the page, starting with the LSB of the instruction with page address 0 and ending with the MSB of the instruction with page address 3F. This provides an efficient way to load the entire Flash page buffer before executing Page Write. Figure 104. Virtual Flash Page Load Register
STROBES
State machine
ADDRESS
TDI
Flash EEPROM Fuses Lock Bits
D A T A
TDO
208
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Virtual Flash Page Read Register
The Virtual Flash Page Read Register is a virtual scan chain with length equal to the number of bits in one Flash page plus eight, 1,032 in total. Internally the Shift Register is 8-bit, and the data are automatically transferred from the Flash data page byte-by-byte. The first eight cycles are used to transfer the first byte to the internal Shift Register, and the bits that are shifted out during these eight cycles should be ignored. Following this initialization, data are shifted out starting with the LSB of the instruction with page address 0 and ending with the MSB of the instruction with page address 3F. This provides an efficient way to read one full Flash page to verify programming. Figure 105. Virtual Flash Page Read Register
STROBES
State machine
TDI ADDRESS
Flash EEPROM Fuses Lock Bits
D A T A
TDO
Programming algorithm
Entering programming mode
All references below of type "1a", "1b", and so on, refer to Table 71. 1. Enter JTAG instruction AVR_RESET and shift 1 in the Reset Register. 2. Enter instruction PROG_ENABLE and shift 1010_0011_0111_0000 in the Programming Enable Register.
Leaving Programming Mode
1. Enter JTAG instruction PROG_COMMANDS. 2. Disable all programming instructions by using no operation instruction 11a. 3. Enter instruction PROG_ENABLE and shift 0000_0000_0000_0000 in the programming Enable Register. 4. Enter JTAG instruction AVR_RESET and shift 0 in the Reset Register. If PROG_ENABLE instruction is not followed by the AVR_RESET instruction, the following algorithm should be used: 1. Enter JTAG instruction PROG_COMMANDS. 2. Disable all programming instructions by using no operation instruction 11a. 3. Enter instruction PROG_ENABLE and shift 0000_0000_0000_0000 in the Programming Enable Register. 4. Enter instruction PROG_ENABLE and shift 0000_0000_0000_0000 in the Programming Enable Register. 5. Wait until the selected Oscillator has started before applying more commands.
209
1457G-AVR-09/03
Performing Chip Erase
1. Enter JTAG instruction PROG_COMMANDS. 2. Start chip erase using programming instruction 1a. 3. Poll for chip erase complete using programming instruction 1b, or wait for tWLRH_CE (refer to Table 67 on page 196).
Programming the Flash
1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Flash write using programming instruction 2a. 3. Load address using programming instructions 2b and 2c. 4. Load data using programming instructions 2d, 2e and 2f. 5. Repeat step 3 and 4 for all 64 instruction words in the page. 6. Write the page using programming instruction 2g. 7. Poll for Flash write complete using programming instruction 2h, or wait for tWLRH_FLASH (refer to Table 67 on page 196). 8. Repeat steps 3 to 7 until all data have been programmed. A more efficient data transfer can be achieved using the PROG_PAGELOAD instruction: 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Flash write using programming instruction 2a. 3. Load the page address using programming instructions 2b and 2c. The 6 LSB are used to address within one page and must be written as 0. 4. Enter JTAG instruction PROG_PAGELOAD. 5. Load the entire page by shifting in all instruction words in the page, starting with the LSB of the first instruction in the page and ending with the MSB of the last instruction in the page. 6. Enter JTAG instruction PROG_COMMANDS. 7. Write the page using programming instruction 2g. 8. Poll for Flash write complete using programming instruction 2h, or wait for tWLRH_FLASH (refer to Table 67 on page 196). 9. Repeat steps 3 to 8 until all data have been programmed.
Reading the Flash
1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Flash read using programming instruction 3a. 3. Load address using programming instructions 3b and 3c. 4. Read data using programming instruction 3d. 5. Repeat steps 3 and 4 until all data have been read. A more efficient data transfer can be achieved using the PROG_PAGEREAD instruction: 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Flash read using programming instruction 3a. 3. Load the page address using programming instructions 3b and 3c. The 6 LSB are used to address within one page and must be written as 0. 4. Enter JTAG instruction PROG_PAGEREAD. 5. Read the entire page by shifting out all instruction words in the page, starting with the LSB of the instruction with page address 0 and ending with the MSB of the instruction with page address 3F. Remember that the first eight bits should be ignored.
210
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
6. Enter JTAG instruction PROG_COMMANDS. 7. Repeat steps 3 to 6 until all data have been read. Programming the EEPROM 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable EEPROM write using programming instruction 4a. 3. Load address using programming instructions 4b and 4c. 4. Load data using programming instructions 4d. 5. Write the data using programming instruction 4e. 6. Poll for EEPROM write complete using programming instruction 4f, or wait for tWLRH (refer to Table 67 on page 196). 7. Repeat steps 3 to 6 until all data have been programmed. Reading the EEPROM 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable EEPROM read using programming instruction 5a. 3. Load address using programming instructions 5b and 5c. 4. Read data using programming instruction 5d. 5. Repeat steps 3 and 4 until all data have been read. Programming the Fuses 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Fuse write using programming instruction 6a. 3. Load data High Byte using programming instructions 6b. A bit value of "0" will program the corresponding fuse, a "1" will unprogram the fuse. 4. Write Fuse High Byte using programming instruction 6c. 5. Poll for Fuse write complete using programming instruction 6d, or wait for tWLRH (refer to Table 67 on page 196). 6. Load data Low Byte using programming instructions 6e. A "0" will program the fuse, a "1" will unprogram the fuse. 7. Write Fuse Low Byte using programming instruction 6f. 8. Poll for Fuse write complete using programming instruction 6g, or wait for tWLRH (refer to Table 67 on page 196). Programming the Lock Bits 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Lock bit write using programming instruction 7a. 3. Load data using programming instructions 7b. A bit value of "0" will program the corresponding lock bit, a "1" will leave the lock bit unchanged. 4. Write Lock bits using programming instruction 7c. 5. Poll for Lock bit write complete using programming instruction 7d, or wait for tWLRH (refer to Table 67 on page 196). Reading the Fuses and Lock Bits 1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Fuse/Lock bit read using programming instruction 8a. 3. To read all Fuses and Lock bits, use programming instruction 8e. To only read Fuse High Byte, use programming instruction 8b. To only read Fuse Low Byte, use programming instruction 8c. To only read Lock bits, use programming instruction 8d.
211
1457G-AVR-09/03
Reading the Signature Bytes
1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Signature byte read using programming instruction 9a. 3. Load address $00 using programming instruction 9b. 4. Read first signature byte using programming instruction 9c. 5. Repeat steps 3 and 4 with address $01 and address $02 to read the second and third signature bytes, respectively.
Reading the Calibration Byte
1. Enter JTAG instruction PROG_COMMANDS. 2. Enable Calibration byte read using programming instruction 10a. 3. Load address $00 using programming instruction 10b. 4. Read the calibration byte using programming instruction 10c.
212
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Electrical Characteristics
Absolute Maximum Ratings*
Operating Temperature .................................. -55C to +125C Storage Temperature ..................................... -65C to +150C Voltage on any Pin except RESET with respect to Ground ................................-0.5V to VCC+0.5V Voltage on RESET with respect to Ground......-0.5V to +13.0V Maximum Operating Voltage ............................................ 6.0V DC Current per I/O Pin ............................................... 40.0 mA DC Current VCC and GND Pins................................ 200.0 mA *NOTICE: Stresses beyond those listed under "Absolute Maximum Ratings" may cause permanent damage to the device. This is a stress rating only and functional operation of the device at these or other conditions beyond those indicated in the operational sections of this specification is not implied. Exposure to absolute maximum rating conditions for extended periods may affect device reliability.
DC Characteristics
TA = -40C to 85C, VCC = 2.7V to 5.5V (Unless Otherwise Noted)
Symbol VIL Parameter Input Low Voltage Condition (Except XTAL1) (XTAL1), CKSEL3 Fuse programmed VIL1 Input Low Voltage (XTAL1), CKSEL3 Fuse unprogrammed Input High Voltage (Except XTAL1, RESET) (XTAL1), CKSEL3 Fuse programmed VIH1 Input High Voltage (XTAL1), CKSEL3 Fuse unprogrammed Input High Voltage Output Low Voltage(3) (Ports A,B,C,D) Output High Voltage(4) (Ports A,B,C,D) Input Leakage Current I/O Pin Input Leakage Current I/O Pin Reset Pull-up Resistor I/O Pin Pull-up Resistor (RESET) IOL = 20 mA, VCC = 5V IOL = 10 mA, VCC = 3V IOH = -3 mA, VCC = 5V IOH = -1.5 mA, VCC = 3V Vcc = 5.5V, pin low (absolute value) Vcc = 5.5V, pin high (absolute value) 100 35 4.2 2.3 8.0 980 500 120 0.8 VCC(2) 0.9 VCC(2) VCC + 0.5 VCC + 0.5 0.6 0.5 V V V V V V A nA k k -0.5 0.6 VCC(2) 0.6 VCC(2) 0.2 Min -0.5 -0.5 Typ Max 0.3 0.3 Units V V V V V
VCC(1) VCC(1) VCC(1)
VIH
VCC + 0.5 VCC + 0.5
VIH2 VOL VOH IIL IIH RRST RI/O
213
1457G-AVR-09/03
DC Characteristics (Continued)
TA = -40C to 85C, VCC = 2.7V to 5.5V (Unless Otherwise Noted)
Symbol Parameter Condition Active 4 MHz, VCC = 3V (ATmega323L) Active 8 MHz, VCC = 5V (ATmega323) Power Supply Current ICC Idle 4 MHz, VCC = 3V (ATmega323L) Idle 8 MHz, VCC = 5V (ATmega323) Power-down mode(5) Analog Comparator Input Offset Voltage Analog Comparator Input Leakage Current Analog Comparator Initialization Delay WDT enabled, VCC = 3V WDT disabled, VCC = 3V VACIO IACLK tACID VCC = 5V Vin = VCC/2 VCC = 5V Vin = VCC/2 VCC = 2.7V VCC = 4.0V -50 750 500 9 <1 2.5 mA Min Typ Max 5 Units mA
15
mA
8 15.0 4.0 40 50
mA A A mV nA ns
Note:
1. "Max" means the highest value where the pin is guaranteed to be read as low 2. "Min" means the lowest value where the pin is guaranteed to be read as high 3. Although each I/O port can sink more than the test conditions (20mA at Vcc = 5V, 10mA at Vcc = 3V) under steady state conditions (non-transient), the following must be observed - PDIP Package: 1] The sum of all IOL, for all ports, should not exceed 200 mA. 2] The sum of all IOL, for port A0 - A7, should not exceed 100 mA. 3] The sum of all IOL, for ports B0 - B7,C0 - C7, D0 - D7 and XTAL2, should not exceed 100 mA - TQFP Package: 1] The sum of all IOL, for all ports, should not exceed 400 mA. 2] The sum of all IOL, for ports A0 - A7, should not exceed 100 mA. 3] The sum of all IOL, for ports B0 - B3, should not exceed 100 mA. 4] The sum of all IOL, for ports B4 - B7, should not exceed 100 mA. 5] The sum of all IOL, for ports C0 - C3, should not exceed 100 mA. 6] The sum of all IOL, for ports C4 - C7, should not exceed 100 mA. 7] The sum of all IOL, for ports D0 - D3 and XTAL2, should not exceed 100 mA. 8] The sum of all IOL, for ports D4 - D7, should not exceed 100 mA If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition. 4. Although each I/O port can source more than the test conditions (3mA at Vcc = 5V, 1.5mA at Vcc = 3V) under steady state conditions (non-transient), the following must be observed - PDIP Package: 1] The sum of all IOH, for all ports, should not exceed 200 mA. 2] The sum of all IOH, for port A0 - A7, should not exceed 100 mA. 3] The sum of all IOH, for ports B0 - B7,C0 - C7, D0 - D7 and XTAL2, should not exceed 100 mA - TQFP Package: 1] The sum of all IOH, for all ports, should not exceed 400 mA. 2] The sum of all IOH, for ports A0 - A7, should not exceed 100 mA. 3] The sum of all IOH, for ports B0 - B3, should not exceed 100 mA. 4] The sum of all IOH, for ports B4 - B7, should not exceed 100 mA. 5] The sum of all IOH, for ports C0 - C3, should not exceed 100 mA. 6] The sum of all IOH, for ports C4 - C7, should not exceed 100 mA. 7] The sum of all IOH, for ports D0 - D3 and XTAL2, should not exceed 100 mA. 8] The sum of all IOH, for ports D4 - D7, should not exceed 100 mA If IOH exceeds the test condition, VOH may exceed the related specification. Pins are not guaranteed to source current greater than the listed test condition. 5. Minimum VCC for Power-down is 2.5V.
214
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
External Clock Drive Waveforms
Figure 106. External Clock Drive Waveforms
lH1 lL1
External Clock Drive
Table 72. External Clock Drive
VCC = 2.7V to 5.5V Symbol 1/tCLCL tCLCL tCHCX tCLCX tCLCH tCHCL Parameter Oscillator Frequency Clock Period High Time Low Time Rise Time Fall Time Min 0 250 100 100 1.6 1.6 Max 4 VCC = 4.0V to 5.5V Min 0 125 50 50 0.5 0.5 Max 8 Units MHz ns ns ns s s
Table 73. External RC Oscillator, Typical Frequencies
R [k] 100 31.5 6.5 Note: C [pF] 70 20 20 f TBD TBD TBD
R should be in the range 3k - 100k, and C should be at least 20pF. The C values given in the table includes pin capacitance. This will vary with package type.
215
1457G-AVR-09/03
Two-wire Serial Interface Characteristics
Table 74 describes the requirements for devices connected to the Two-wire Serial Bus. The ATmega323 Two-wire Serial Interface meets or exceeds these requirements under the noted conditions. Timing symbols refer to Figure 107. Table 74. Two-wire Serial Bus Requirements
Symbol
VIL VIH (1) Vhys VOL tof (1)
Parameter
Condition
Min
Max
Units
Input Low-voltage Input High-voltage Hysteresis of Schmitt Trigger Inputs Output Low-voltage Output Fall Time from VIHmin to VILmax Spikes Suppressed by Input Filter Input Current each I/O Pin 0.1VCC < Vi < 0.9VCC
(4) (5)
-0.5 0.7 VCC 0.05 VCC(2) 3 mA sink current 10 pF < Cb < 400 pF
(3)
0.3 VCC VCC + 0.5 - 0.4
(3)(2)
V V V V ns ns A pF kHz s s s s s s s s s s ns ns s s s s
0 20 + 0.1Cb 0 -10 -
(1) (1)
250 50(2) 10 10 400 - - - - - - - - 3.45 0.9 - - - - - -
tSP
Ii Ci
(1)
Capacitance for each I/O Pin SCL Clock Frequency Hold Time (repeated) START Condition fCK > max(16fSCL, 250kHz) fSCL 100 kHz fSCL > 100 kHz Low Period of the SCL Clock fSCL 100 kHz
(6) (7)
fSCL tHD;STA
0 4.0 0.6 4.7 1.3 4.0 0.6 4.7 0.6 0 0 250 100 4.0 0.6 4.7 1.3
tLOW
fSCL > 100 kHz High period of the SCL clock
tHIGH
fSCL 100 kHz fSCL > 100 kHz fSCL 100 kHz fSCL > 100 kHz fSCL 100 kHz fSCL > 100 kHz fSCL 100 kHz fSCL > 100 kHz fSCL 100 kHz fSCL > 100 kHz fSCL 100 kHz fSCL > 100 kHz
tSU;STA
Set-up time for a repeated START condition
tHD;DAT
Data hold time
tSU;DAT
Data setup time
tSU;STO
Setup time for STOP condition Bus free time between a STOP and START condition 1. 2. 3. 4. 5.
tBUF Notes:
In ATmega323, this parameter is characterized and not 100% tested. Required only for fSCL > 100 kHz. Cb = capacitance of one bus line in pF. fCK = CPU clock frequency This requirement applies to all ATmega323 Two-wire Serial Interface operation. Other devices connected to the Two-wire Serial Bus need only obey the general fSCL requirement. 6. The actual low period generated by the ATmega323 Two-wire Serial Interface is (1/fSCL - 2/fCK), thus fCK must be greater than 6 MHz for the low time requirement to be strictly met at fSCL = 100 kHz. 7. The actual low period generated by the ATmega323 Two-wire Serial Interface is (1/fSCL - 2/fCK), thus the low time requirement will not be strictly met for fSCL > 308 kHz when fCK = 8 MHz. Still, ATmega323 devices connected to the bus may
216
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
communicate at full speed (400 kHz) with other ATmega323 devices, as well as any other device with a proper tLOW acceptance margin.
Figure 107. Two-wire Serial Bus timing
tof tLOW SCL tSU;STA SDA tHD;STA tHD;DAT tSU;DAT tSU;STO tHIGH tLOW
tBUF
217
1457G-AVR-09/03
ATmega323 Typical Characteristics - Preliminary Data
The following charts show typical behavior. These figures are not tested during manufacturing. All current consumption measurements are performed with all I/O pins configured as inputs and with internal pull-ups enabled. A sine wave generator with railto-rail output is used as clock source. The power consumption in Power-down mode is independent of clock selection. The current consumption is a function of several factors such as: operating voltage, operating frequency, loading of I/O pins, switching rate of I/O pins, code executed and ambient temperature. The dominating factors are operating voltage and frequency. The current drawn from capacitive loaded pins may be estimated (for one pin) as CL*VCC*f where CL = load capacitance, VCC = operating voltage and f = average switching frequency of I/O pin. The parts are characterized at frequencies higher than test limits. Parts are not guaranteed to function properly at frequencies higher than the ordering code indicates. The difference between current consumption in Power-down mode with Watchdog Timer enabled and Power-down mode with Watchdog Timer disabled represents the differential current drawn by the Watchdog timer. Figure 108. Active Supply Current vs. Frequency
ACTIVE SUPPLY CURRENT vs. FREQUENCY
TA= 25C
60
50
Vcc= 6V Vcc= 5.5V
40
I cc(mA)
30
Vcc= 5V Vcc= 4.5V
20
Vcc= 4V Vcc= 3.6V Vcc= 3.3V Vcc= 3.0V Vcc= 2.7V
10
0
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Frequency (MHz)
218
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Figure 109. Active Supply Current vs. VCC
ACTIVE SUPPLY CURRENT vs. Vcc
FREQUENCY = 4 MHz 20 18
TA = 85C
16 14 12
I cc(mA)
TA = 25C
10 8 6 4 2 0 2.5 3 3.5 4
Vcc(V)
4.5
5
5.5
6
Figure 110. Active Supply Current vs. VCC, Device Clocked by Internal Oscillator
ACTIVE SUPPLY CURRENT vs. Vcc DEVICE CLOCKED BY 1.0MHz INTERNAL RC OSCILLATOR
5 4.5 4 3.5 3
I cc(mA) TA = 85C TA = 25C
2.5 2 1.5 1 0.5 0
2.5 3 3.5 4
Vcc(V)
4.5
5
5.5
6
219
1457G-AVR-09/03
Figure 111. Active Supply Current vs. VCC, Device Clocked by External 32kHz Crystal
ACTIVE SUPPLY CURRENT vs. Vcc
DEVICE CLOCKED BY 32KHz CRYSTAL 1.4 1.2 1 0.8
I cc(mA) TA = 25C TA = 85C
0.6 0.4 0.2 0 2.5 3 3.5 4
Vcc(V)
4.5
5
5.5
6
Figure 112. Idle Supply Current vs. Frequency
IDLE SUPPLY CURRENT vs. FREQUENCY
TA= 25C 35 30 25 20
Vcc= 5V Vcc= 4.5V Vcc= 4V Vcc= 3.6V Vcc= 3.3V Vcc= 3.0V Vcc= 2.7V Vcc= 6V Vcc= 5.5V
I cc(mA)
15 10 5 0 0 1 2 3 4 5 6 7 8 9 10
11
12
13
14
15
Frequency (MHz)
220
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Figure 113. Idle Supply Current vs. VCC
IDLE SUPPLY CURRENT vs. Vcc
FREQUENCY = 4 MHz
12
10
TA = 85C TA = 25C
8
I cc(mA)
6
4
2
0
2.5 3 3.5 4
Vcc(V)
4.5
5
5.5
6
Figure 114. Idle Supply Current vs. VCC, Device Clocked by Internal Oscillator
IDLE SUPPLY CURRENT vs. Vcc DEVICE CLOCKED BY 1.0MHz INTERNAL RC OSCILLATOR
2.5
2
TA = 85C TA = 25C
1.5
I cc(mA)
1
0.5
0
2.5
3
3.5
4
Vcc(V)
4.5
5
5.5
6
221
1457G-AVR-09/03
Figure 115. Idle Supply Current vs. VCC, Device Clocked by External 32kHz Crystal
IDLE SUPPLY CURRENT vs. Vcc DEVICE CLOCKED BY 32KHz CRYSTAL
100 90
TA = 85C
80 70 60
I cc(A) TA = 25C
50 40 30 20 10 0 2.5 3 3.5 4
Vcc(V)
4.5
5
5.5
6
Figure 116. Power-down Supply Current vs. VCC
POWER DOWN SUPPLY CURRENT vs. Vcc
WATCHDOG TIMER DISABLED
8 7 6 5
I cc(A) TA = 85C
4 3 2 1 0 2.5 3 3.5 4
Vcc(V) TA = 45C TA = 25C TA = 70C
4.5
5
5.5
6
222
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Figure 117. Power-down Supply Current vs. VCC
POWER DOWN SUPPLY CURRENT vs. Vcc
WATCHDOG TIMER ENABLED 100 90 80 70 60
I cc(A) TA = 25C
TA = 85C
50 40 30 20 10 0 2.5 3 3.5 4
Vcc(V)
4.5
5
5.5
6
Figure 118. Power-save Supply Current vs. VCC
POWER SAVE SUPPLY CURRENT vs. Vcc
WATCHDOG TIMER DISABLED 30
25
TA = 85C TA = 25C I cc(A)
20
15
10
5
0 2.5 3 3.5 4
Vcc(V)
4.5
5
5.5
6
223
1457G-AVR-09/03
Figure 119. Analog Comparator Current vs. VCC
ANALOG COMPARATOR CURRENT vs. Vcc
0.9 0.8 0.7 0.6
TA = 85C I cc(mA) TA = 25C
0.5 0.4 0.3 0.2 0.1 0 2 2.5 3 3.5
Vcc(V)
4
4.5
5
5.5
6
Analog comparator offset voltage is measured as absolute offset Figure 120. Analog Comparator Offset Voltage vs. Common Mode Voltage
ANALOG COMPARATOR OFFSET VOLTAGE vs. COMMON MODE VOLTAGE Vcc = 5V
18 16 14
Offset Voltage (mV)
TA = 25C
12 10 8 6 4 2 0 0 0.5 1 1.5 2 2.5 3 3.5 4
TA = 85C
4.5
5
Common Mode Voltage (V)
224
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Figure 121. Analog Comparator Offset voltage vs. Common Mode Voltage
ANALOG COMPARATOR OFFSET VOLTAGE vs. COMMON MODE VOLTAGE Vcc = 2.7V
10
TA = 25C
8
Offset Voltage (mV)
6
TA = 85C
4
2
0 0 0.5 1 1.5 Common Mode Voltage (V) 2 2.5 3
Figure 122. Analog Comparator Input Leakage Current
ANALOG COMPARATOR INPUT LEAKAGE CURRENT
VCC = 6V TA = 25C
60 50 40
(nA) I
ACLK
30 20 10 0 -10 0 0.5 1 1.5 2 2.5 3 3.5
VIN (V)
4
4.5
5
5.5
6
6.5
7
225
1457G-AVR-09/03
Figure 123. Calibrated RC Oscillator Frequency vs. VCC
CALIBRATED RC OSCILLATOR FREQUENCY vs. OPERATING VOLTAGE
1.02
TA = 25C TA = 45C TA = 70C
1 0.98 0.96 0.94 0.92 0.9 0.88 2 2.5 3 3.5 4
Vcc(V) TA = 85C
FRc (MHz)
4.5
5
5.5
6
Figure 124. Watchdog Oscillator Frequency vs. VCC
WATCHDOG OSCILLATOR FREQUENCY vs. Vcc
1600
TA = 25C
1400 1200 1000 800 600 400 200 0 2 2.5 3 3.5 4
Vcc (V)
TA = 85C
F RC (KHz)
4.5
5
5.5
6
Sink and source capabilities of I/O ports are measured on one pin at a time.
226
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Figure 125. Pull-Up Resistor Current vs. Input Voltage
PULL-UP RESISTOR CURRENT vs. INPUT VOLTAGE
Vcc = 5V 120
TA = 25C
100
TA = 85C
80
OP (A)
I
60
40
20
0 0 0.5 1 1.5 2 2.5 VOP (V) 3 3.5 4 4.5 5
Figure 126. Pull-Up Resistor Current vs. Input Voltage
PULL-UP RESISTOR CURRENT vs. INPUT VOLTAGE
Vcc = 2.7V 30
TA = 25C
25
TA = 85C
20
OP (A)
15
I
10
5
0 0 0.5 1 1.5 VOP (V) 2 2.5 3
227
1457G-AVR-09/03
Figure 127. I/O Pin Sink Current vs. Output Voltage
I/O PIN SINK CURRENT vs. OUTPUT VOLTAGE
Vcc = 5V 70
TA = 25C
60
TA = 85C
50 40
OL (mA)
30 20 10 0 0 0.5 1 1.5 VOL (V) 2 2.5 3
Figure 128. I/O Pin Source Current vs. Output Voltage
I/O PIN SOURCE CURRENT vs. OUTPUT VOLTAGE
Vcc = 5V 20 18 16 14 12
OH (mA)
I
TA = 25C
TA = 85C
10 8 6 4 2 0 0 0.5 1 1.5 2 2.5 VOH (V) 3 3.5 4 4.5 5
228
ATmega323(L)
1457G-AVR-09/03
I
ATmega323(L)
Figure 129. I/O Pin Sink Current vs. Output Voltage
I/O PIN SINK CURRENT vs. OUTPUT VOLTAGE
Vcc = 2.7V 25
TA = 25C
20
TA = 85C
15
OL (mA)
10
I
5
0 0 0.5 1 VOL (V) 1.5 2
Figure 130. I/O Pin Source Current vs. Output Voltage
I/O PIN SOURCE CURRENT vs. OUTPUT VOLTAGE
Vcc = 2.7V 6
TA = 25C
5
TA = 85C
4
OH (mA)
3
I
2
1
0 0 0.5 1 1.5 VOH (V) 2 2.5 3
229
1457G-AVR-09/03
Figure 131. I/O Pin Input Threshold Voltage vs. VCC
I/O PIN INPUT THRESHOLD VOLTAGE vs. Vcc
TA = 25C
2.5
2
Threshold Voltage (V)
1.5
1
0.5
0 2.7 4.0 Vcc 5.0
Figure 132. I/O Pin Input Hysteresis vs. VCC
I/O PIN INPUT HYSTERESIS vs. Vcc
TA = 25C
0.18 0.16 0.14
Input hysteresis (V)
0.12 0.1 0.08 0.06 0.04 0.02 0 2.7 4.0 Vcc 5.0
230
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Register Summary
Address
$3F ($5F) $3E ($5E) $3D ($5D) $3C ($5C) $3B ($5B) $3A ($5A) $39 ($59) $38 ($58) $37 ($57) $36 ($56) $35 ($55) $34 ($54) $33 ($53) $32 ($52) $31 ($51) $30 ($50) $2F ($4F) $2E ($4E) $2D ($4D) $2C ($4C) $2B ($4B) $2A ($4A) $29 ($49) $28 ($48) $27 ($47) $26 ($46) $25 ($45) $24 ($44) $23 ($43) $22 ($42) $21 ($41) $20 ($40) $1F ($3F) $1E ($3E) $1D ($3D) $1C ($3C) $1B ($3B) $1A ($3A) $19 ($39) $18 ($38) $17 ($37) $16 ($36) $15 ($35) $14 ($34) $13 ($33) $12 ($32) $11 ($31) $10 ($30) $0F ($2F) $0E ($2E) $0D ($2D) $0C ($2C) $0B ($2B) $0A ($2A) $09 ($29) $08 ($28) $07 ($27) $06 ($26) $05 ($25) $04 ($24) $03 ($23) $02 ($22)
Name
SREG SPH SPL OCR0 GICR GIFR TIMSK TIFR SPMCR TWCR MCUCR MCUCSR TCCR0 TCNT0 OSCCAL OCRD SFIOR TCCR1A TCCR1B TCNT1H TCNT1L OCR1AH OCR1AL OCR1BH OCR1BL ICR1H ICR1L TCCR2 TCNT2 OCR2 ASSR WDTCR UBRRH UCSRC EEARH EEARL EEDR EECR PORTA DDRA PINA PORTB DDRB PINB PORTC DDRC PINC PORTD DDRD PIND SPDR SPSR SPCR UDR UCSRA UCSRB UBRRL ACSR ADMUX ADCSR ADCH ADCL TWDR TWAR
Bit 7
I - SP7 INT1 INTF1 OCIE2 OCF2 - TWINT SE JTD FOC0
Bit 6
T - SP6 INT0 INTF0 TOIE2 TOV2 ASB TWEA SM2 ISC2 PWM0
Bit 5
H - SP5 INT2 INTF2 TICIE1 ICF1 - TWSTA SM1 - COM01
Bit 4
S - SP4 - - OCIE1A OCF1A ASRE TWSTO SM0 JTRF COM00
Bit 3
V SP11 SP3 - - OCIE1B OCF1B BLBSET TWWC ISC11 WDRF CTC0
Bit 2
N SP10 SP2 - - TOIE1 TOV1 PGWRT TWEN ISC10 BORF CS02
Bit 1
Z SP9 SP1 IVSEL - OCIE0 OCF0 PGERS - ISC01 EXTRF CS01
Bit 0
C SP8 SP0 IVCE - TOIE0 TOV0 SPMEN TWIE ISC00 PORF CS00
Page
page 21 page 22 page 22 page 47 page 33 page 34 page 36 page 36 page 183 page 104 page 37 page 30 page 47 page 49 page 41 page 161
Timer/Counter0 Output Compare Register
Timer/Counter0 (8 Bits) Oscillator Calibration Register On-chip Debug Register - COM1A1 ICNC1 - COM1A0 ICES1 - COM1B1 - - COM1B0 - ACME FOC1A CTC1 PUD FOC1B CS12 PSR2 PWM11 CS11 PSR10 PWM10 CS10
page 45 page 56 page 57 page 58 page 58 page 59 page 59 page 59 page 59 page 60 page 60
Timer/Counter1 - Counter Register High Byte Timer/Counter1 - Counter Register Low Byte Timer/Counter1 - Output Compare Register A High Byte Timer/Counter1 - Output Compare Register A Low Byte Timer/Counter1 - Output Compare Register B High Byte Timer/Counter1 - Output Compare Register B Low Byte Timer/Counter1 - Input Capture Register High Byte Timer/Counter1 - Input Capture Register Low Byte FOC2 PWM2 COM21 COM20 CTC2 CS22 CS21 CS20 Timer/Counter2 (8 Bits) Timer/Counter2 Output Compare Register - - URSEL URSEL - EEAR7 - PORTA7 DDA7 PINA7 PORTB7 DDB7 PINB7 PORTC7 DDC7 PINC7 PORTD7 DDD7 PIND7 SPIF SPIE RXC RXCIE ACD REFS1 ADEN - - - UMSEL - EEAR6 - PORTA6 DDA6 PINA6 PORTB6 DDB6 PINB6 PORTC6 DDC6 PINC6 PORTD6 DDD6 PIND6 WCOL SPE TXC TXCIE ACBG REFS0 ADSC - - - UPM1 - EEAR5 - PORTA5 DDA5 PINA5 PORTB5 DDB5 PINB5 PORTC5 DDC5 PINC5 PORTD5 DDD5 PIND5 - DORD UDRE UDRIE ACO ADLAR ADFR - WDTOE - UPM0 - EEAR4 - PORTA4 DDA4 PINA4 PORTB4 DDB4 PINB4 PORTC4 DDC4 PINC4 PORTD4 DDD4 PIND4 - MSTR FE RXEN ACI MUX4 ADIF USBS - EEAR3 EERIE PORTA3 DDA3 PINA3 PORTB3 DDB3 PINB3 PORTC3 DDC3 PINC3 PORTD3 DDD3 PIND3 - CPOL DOR TXEN ACIE MUX3 ADIE - EEAR2 EEMWE PORTA2 DDA2 PINA2 PORTB2 DDB2 PINB2 PORTC2 DDC2 PINC2 PORTD2 DDD2 PIND2 - CPHA PE UCSZ2 ACIC MUX2 ADPS2 AS2 WDE TCN2UB WDP2 UCSZ1 OCR2UB WDP1 UBRR[11:8] UCSZ0 EEAR9 EEAR1 EEWE PORTA1 DDA1 PINA1 PORTB1 DDB1 PINB1 PORTC1 DDC1 PINC1 PORTD1 DDD1 PIND1 - SPR1 U2X RXB8 ACIS1 MUX1 ADPS1 UCPOL EEAR8 EEAR0 EERE PORTA0 DDA0 PINA0 PORTB0 DDB0 PINB0 PORTC0 DDC0 PINC0 PORTD0 DDD0 PIND0 SPI2X SPR0 MPCM TXB8 ACIS0 MUX0 ADPS0 TCR2UB WDP0
page 47 page 49 page 49 page 52 page 64 page 98 page 97 page 66 page 66 page 66 page 67 page 137 page 137 page 137 page 139 page 139 page 139 page 146 page 146 page 146 page 151 page 151 page 151 page 73 page 72 page 71 page 94 page 94 page 96 page 98 page 125 page 132 page 133 page 134 page 134 page 106
EEPROM Data Register
SPI Data Register
USART I/O Data Register
USART Baud Rate Register Low Byte
ADC Data Register High Byte ADC Data Register Low Byte Two-wire Serial Interface Data Register TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE
page 107
231
1457G-AVR-09/03
Address
$01 ($21) $00 ($20)
Name
TWSR TWBR
Bit 7
TWS7
Bit 6
TWS6
Bit 5
TWS5
Bit 4
TWS4
Bit 3
TWS3
Bit 2
-
Bit 1
-
Bit 0
-
Page
page 106 page 104
Two-wire Serial Interface Bit Rate Register
Notes:
1. When the OCDEN Fuse is unprogrammed, the OSCCAL Register is always accessed on this address. Refer to the debugger specific documentation for details on how to use the OCDR Register. 2. Refer to the USART description for details on how to access UBRRH and UCSRC. 3. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O Memory addresses should never be written. 4. Some of the Status Flags are cleared by writing a logical one to them. Note that the CBI and SBI instructions will operate on all bits in the I/O Register, writing a one back into any flag read as set, thus clearing the flag. The CBI and SBI instructions work with registers $00 to $1F only.
232
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Instruction Set Summary
Mnemonics
ADD ADC ADIW SUB SUBI SBC SBCI SBIW AND ANDI OR ORI EOR COM NEG SBR CBR INC DEC TST CLR SER MUL MULS MULSU FMUL FMULS FMULSU RJMP IJMP JMP RCALL ICALL CALL RET RETI CPSE CP CPC CPI SBRC SBRS SBIC SBIS BRBS BRBC BREQ BRNE BRCS BRCC BRSH BRLO BRMI BRPL BRGE BRLT BRHS BRHC BRTS BRTC BRVS BRVC Rd,Rr Rd,Rr Rd,Rr Rd,K Rr, b Rr, b P, b P, b s, k s, k k k k k k k k k k k k k k k k k k k k
Operands
Rd, Rr Rd, Rr Rdl,K Rd, Rr Rd, K Rd, Rr Rd, K Rdl,K Rd, Rr Rd, K Rd, Rr Rd, K Rd, Rr Rd Rd Rd,K Rd,K Rd Rd Rd Rd Rd Rd, Rr Rd, Rr Rd, Rr Rd, Rr Rd, Rr Rd, Rr k
Description
Add two Registers Add with Carry two Registers Add Immediate to Word Subtract two Registers Subtract Constant from Register Subtract with Carry two Registers Subtract with Carry Constant from Reg. Subtract Immediate from Word Logical AND Registers Logical AND Register and Constant Logical OR Registers Logical OR Register and Constant Exclusive OR Registers One's Complement Two's Complement Set Bit(s) in Register Clear Bit(s) in Register Increment Decrement Test for Zero or Minus Clear Register Set Register Multiply Unsigned Multiply Signed Multiply Signed with Unsigned Fractional Multiply Unsigned Fractional Multiply Signed Fractional Multiply Signed with Unsigned Relative Jump Indirect Jump to (Z) Direct Jump Relative Subroutine Call Indirect Call to (Z) Direct Subroutine Call Subroutine Return Interrupt Return Compare, Skip if Equal Compare Compare with Carry Compare Register with Immediate Skip if Bit in Register Cleared Skip if Bit in Register is Set Skip if Bit in I/O Register Cleared Skip if Bit in I/O Register is Set Branch if Status Flag Set Branch if Status Flag Cleared Branch if Equal Branch if Not Equal Branch if Carry Set Branch if Carry Cleared Branch if Same or Higher Branch if Lower Branch if Minus Branch if Plus Branch if Greater or Equal, Signed Branch if Less Than Zero, Signed Branch if Half Carry Flag Set Branch if Half Carry Flag Cleared Branch if T Flag Set Branch if T Flag Cleared Branch if Overflow Flag is Set Branch if Overflow Flag is Cleared
Operation
Rd Rd + Rr Rd Rd + Rr + C Rdh:Rdl Rdh:Rdl + K Rd Rd - Rr Rd Rd - K Rd Rd - Rr - C Rd Rd - K - C Rdh:Rdl Rdh:Rdl - K Rd Rd * Rr Rd Rd * K Rd Rd v Rr Rd Rd v K Rd Rd Rr Rd $FF - Rd Rd $00 - Rd Rd Rd v K Rd Rd * ($FF - K) Rd Rd + 1 Rd Rd - 1 Rd Rd * Rd Rd Rd Rd Rd $FF R1:R0 Rd x Rr R1:R0 Rd x Rr R1:R0 Rd x Rr
Flags
Z,C,N,V,H Z,C,N,V,H Z,C,N,V,S Z,C,N,V,H Z,C,N,V,H Z,C,N,V,H Z,C,N,V,H Z,C,N,V,S Z,N,V Z,N,V Z,N,V Z,N,V Z,N,V Z,C,N,V Z,C,N,V,H Z,N,V Z,N,V Z,N,V Z,N,V Z,N,V Z,N,V None Z,C Z,C Z,C Z,C Z,C Z,C None None None None None None None I None Z, N,V,C,H Z, N,V,C,H Z, N,V,C,H None None None None None None None None None None None None None None None None None None None None None None
#Clocks
1 1 2 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 4 4 4 1/2/3 1 1 1 1/2/3 1/2/3 1/2/3 1/2/3 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2
ARITHMETIC AND LOGIC INSTRUCTIONS
1 R1:R0 (Rd x Rr) << 1 R1:R0 (Rd x Rr) << 1
PC PC + k + 1 PC Z PC k PC PC + k + 1 PC Z PC k PC Stack PC Stack if (Rd = Rr) PC PC + 2 or 3 Rd - Rr Rd - Rr - C Rd - K if (Rr(b)=0) PC PC + 2 or 3 if (Rr(b)=1) PC PC + 2 or 3 if (P(b)=0) PC PC + 2 or 3 if (P(b)=1) PC PC + 2 or 3 if (SREG(s) = 1) then PCPC+k + 1 if (SREG(s) = 0) then PCPC+k + 1 if (Z = 1) then PC PC + k + 1 if (Z = 0) then PC PC + k + 1 if (C = 1) then PC PC + k + 1 if (C = 0) then PC PC + k + 1 if (C = 0) then PC PC + k + 1 if (C = 1) then PC PC + k + 1 if (N = 1) then PC PC + k + 1 if (N = 0) then PC PC + k + 1 if (N V= 0) then PC PC + k + 1 if (N V= 1) then PC PC + k + 1 if (H = 1) then PC PC + k + 1 if (H = 0) then PC PC + k + 1 if (T = 1) then PC PC + k + 1 if (T = 0) then PC PC + k + 1 if (V = 1) then PC PC + k + 1 if (V = 0) then PC PC + k + 1
R1:R0 (Rd x Rr) <<
BRANCH INSTRUCTIONS
233
1457G-AVR-09/03
Mnemonics
BRIE BRID MOV MOVW LDI LD LD LD LD LD LD LDD LD LD LD LDD LDS ST ST ST ST ST ST STD ST ST ST STD STS LPM LPM LPM SPM IN OUT PUSH POP SBI CBI LSL LSR ROL ROR ASR SWAP BSET BCLR BST BLD SEC CLC SEN CLN SEZ CLZ SEI CLI SES CLS SEV CLV SET CLT SEH
Operands
k k Rd, Rr Rd, Rr Rd, K Rd, X Rd, X+ Rd, - X Rd, Y Rd, Y+ Rd, - Y Rd,Y+q Rd, Z Rd, Z+ Rd, -Z Rd, Z+q Rd, k X, Rr X+, Rr - X, Rr Y, Rr Y+, Rr - Y, Rr Y+q,Rr Z, Rr Z+, Rr -Z, Rr Z+q,Rr k, Rr Rd, Z Rd, Z+ Rd, P P, Rr Rr Rd P,b P,b Rd Rd Rd Rd Rd Rd s s Rr, b Rd, b
Description
Branch if Interrupt Enabled Branch if Interrupt Disabled Move Between Registers Copy Register Word Load Immediate Load Indirect Load Indirect and Post-Inc. Load Indirect and Pre-Dec. Load Indirect Load Indirect and Post-Inc. Load Indirect and Pre-Dec. Load Indirect with Displacement Load Indirect Load Indirect and Post-Inc. Load Indirect and Pre-Dec. Load Indirect with Displacement Load Direct from SRAM Store Indirect Store Indirect and Post-Inc. Store Indirect and Pre-Dec. Store Indirect Store Indirect and Post-Inc. Store Indirect and Pre-Dec. Store Indirect with Displacement Store Indirect Store Indirect and Post-Inc. Store Indirect and Pre-Dec. Store Indirect with Displacement Store Direct to SRAM Load Program Memory Load Program Memory Load Program Memory and Post-Inc Store Program Memory In Port Out Port Push Register on Stack Pop Register from Stack Set Bit in I/O Register Clear Bit in I/O Register Logical Shift Left Logical Shift Right Rotate Left Through Carry Rotate Right Through Carry Arithmetic Shift Right Swap Nibbles Flag Set Flag Clear Bit Store from Register to T Bit load from T to Register Set Carry Clear Carry Set Negative Flag Clear Negative Flag Set Zero Flag Clear Zero Flag Global Interrupt Enable Global Interrupt Disable Set Signed Test Flag Clear Signed Test Flag Set Twos Complement Overflow. Clear Twos Complement Overflow Set T in SREG Clear T in SREG Set Half Carry Flag in SREG
Operation
if ( I = 1) then PC PC + k + 1 if ( I = 0) then PC PC + k + 1 Rd Rr Rd+1:Rd Rr+1:Rr Rd K Rd (X) Rd (X), X X + 1 X X - 1, Rd (X) Rd (Y) Rd (Y), Y Y + 1 Y Y - 1, Rd (Y) Rd (Y + q) Rd (Z) Rd (Z), Z Z+1 Z Z - 1, Rd (Z) Rd (Z + q) Rd (k) (X) Rr (X) Rr, X X + 1 X X - 1, (X) Rr (Y) Rr (Y) Rr, Y Y + 1 Y Y - 1, (Y) Rr (Y + q) Rr (Z) Rr (Z) Rr, Z Z + 1 Z Z - 1, (Z) Rr (Z + q) Rr (k) Rr R0 (Z) Rd (Z) Rd (Z), Z Z+1 (Z) R1:R0 Rd P P Rr Stack Rr Rd Stack I/O(P,b) 1 I/O(P,b) 0 Rd(n+1) Rd(n), Rd(0) 0 Rd(n) Rd(n+1), Rd(7) 0 Rd(0)C,Rd(n+1) Rd(n),CRd(7) Rd(7)C,Rd(n) Rd(n+1),CRd(0) Rd(n) Rd(n+1), n=0..6 Rd(3..0)Rd(7..4),Rd(7..4)Rd(3..0) SREG(s) 1 SREG(s) 0 T Rr(b) Rd(b) T C1 C0 N1 N0 Z1 Z0 I1 I 0 S1 S0 V1 V0 T1 T0 H1
Flags
None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None Z,C,N,V Z,C,N,V Z,C,N,V Z,C,N,V Z,C,N,V None SREG(s) SREG(s) T None C C N N Z Z I I S S V V T T H
#Clocks
1/2 1/2 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 1 1 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
DATA TRANSFER INSTRUCTIONS
BIT AND BIT-TEST INSTRUCTIONS
234
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Mnemonics
CLH NOP SLEEP WDR BREAK
Operands
Description
Clear Half Carry Flag in SREG No Operation Sleep Watchdog Reset Break
Operation
H0 (see specific descr. for Sleep function) (see specific descr. for WDR/timer) For On-chip Debug Only
Flags
H None None None None
#Clocks
1 1 1 1 N/A
235
1457G-AVR-09/03
Ordering Information
Speed (MHz) 4 Power Supply 2.7 - 5.5V Ordering Code ATmega323L-4AC ATmega323L-4PC ATmega323L-4AI ATmega323L-4PI 8 4.0 - 5.5V ATmega323-8AC ATMEGA323-8PC ATmega323-8AI ATmega323-8PI Package 44A 40P6 44A 40P6 44A 40P6 44A 40P6 Operation Range Commercial (0C to 70C) Industrial (-40C to 85C) Commercial (0C to 70C) Industrial (-40C to 85C)
Package Type 44A 40P6 44-lead, Thin (1.0 mm) Plastic Gull Wing Quad Flat Package (TQFP) 40-pin, 0.600" Wide, Plastic Dual Inline Package (PDIP)
236
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Packaging Information
44A
D
Marked Pin# 1 ID
E
SEATING PLANE
TOP VIEW
A1 A3 A
L D2
Pin #1 Corner
SIDE VIEW
COMMON DIMENSIONS (Unit of Measure = mm)
E2
SYMBOL A A1 A3 b D
MIN 0.80 -
NOM 0.90 0.02 0.25 REF
MAX 1.00 0.05
NOTE
0.18
0.23 7.00 BSC
0.30
b
BOTTOM VIEW
e
D2 E E2 e
5.00
5.20 7.00 BSC
5.40
5.00
5.20 0.50 BSC
5.40
Notes: 1. JEDEC Standard MO-220, Fig. 1 (SAW Singulation) VKKD-1.
L
0.35
0.55
0.75
01/15/03 TITLE 2325 Orchard Parkway 44M1, 44-pad, 7 x 7 x 1.0 mm Body, Lead Pitch 0.50 mm San Jose, CA 95131 Micro Lead Frame Package (MLF) DRAWING NO. REV. 44M1 C
R
237
1457G-AVR-09/03
40P6
D
PIN 1
E1
A
SEATING PLANE
L B1 e E B
A1
C eB
0 ~ 15 REF
SYMBOL A A1 D E E1 B
COMMON DIMENSIONS (Unit of Measure = mm) MIN - 0.381 52.070 15.240 13.462 0.356 1.041 3.048 0.203 15.494 NOM - - - - - - - - - - 2.540 TYP MAX 4.826 - 52.578 Note 2 15.875 13.970 Note 2 0.559 1.651 3.556 0.381 17.526 NOTE
Notes:
1. This package conforms to JEDEC reference MS-011, Variation AC. 2. Dimensions D and E1 do not include mold Flash or Protrusion. Mold Flash or Protrusion shall not exceed 0.25 mm (0.010").
B1 L C eB e
09/28/01 2325 Orchard Parkway San Jose, CA 95131 TITLE 40P6, 40-lead (0.600"/15.24 mm Wide) Plastic Dual Inline Package (PDIP) DRAWING NO. REV. 40P6 B
R
238
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Errata for ATmega323 Rev. B
* * * * * * *
Interrupts Abort TWI Power-down TWI Master Does not Accept Spikes on Bus Lines TWCR Write Operations Ignored when Immediately Repeated PWM not Phase Correct TWI is Speed Limited in Slave Mode Problems with UBRR Settings Missing OverRun Flag and Fake Frame Error in USART
7. Interrupts Abort TWI Power-down TWI Power-down operation may wake up by other interrupts. If an interrupt (e.g., INT0) occurs during TWI Power-down address watch and wakes up the CPU, the TWI aborts operation and returns to its idle state. If the interrupt occurs in the middle of a Power-down Address Match (i.e., during reading of a slave address), the received address will be lost and the Slave will not return an ACN. Problem Fix/Workaround Ensure that the TWI Address Match is the only enabled interrupt when entering Power-down. The Master can handle this by resending the request if NACH is received. 6. TWI Master Does not Accept Spikes on Bus Lines When the part operates as Master, and the bus is idle (SDA = 1; SCL = 1), generating a short spike on SDA (SDA = 0 for a short interval), no interrupt is generated, and the status code is still $F8 (idle). But when the software initiates a new start condition and clears TWINT, nothing happens on SDA or SCL, and TWINT is never set again. Problem Fix/Workaround Either of the following: 1. Ensure no spikes occur on SDA or SCL lines. 2. Generate a valid START condition followed by a STOP condition on the bus. This provokes a bus error reported as a TWI interrupt with status code $00. 3. In a Single-master system, the user should write the TWSTO bit immediately before writing the TWSTA bit. 5. TWCR Write Operation Ignored when Immediately Repeated Repeated write to TWCR must be delayed. If a write operation to TWCR is immediately followed by another write operation to TWCR, the first write operation may be ignored. Problem Fix/Workaround Ensure at least one instruction (e.g., NOP) is executed between two writes to TWCR. 4. PWM not Phase Correct In phase-correct PWM mode, a change from OCRx = TOP to anything less than TOP does not change the OCx output. This gives a phase error in the following period. Problem Fix/Workaround Make sure this issue is not harmful to the application.
239
1457G-AVR-09/03
3. TWI is Speed Limited in Slave Mode When the Two-wire Serial Interface operates in Slave mode, frames may be undetected if the CPU frequency is less than 64 times the bus frequency. Problem Fix/Workaround Ensure that the CPU frequency is at least 64 times the TWI bus frequency. 2. Problems with UBRR Settings The baud rate corresponding to the previous UBRR setting is used for the first transmitted/received bit when either UBRRH or UBRRL is written. This will disturb communication if the UBRR is changed from a very high to a very low baud rate setting, as the internal baud rate counter will have to count down to zero before using the new setting. In addition, writing to UBRRL incorrectly clears the UBRRH setting. Problem Fix/Workaround UBRRH must be written after UBRRL because setting UBRRL clears UBRRH. By doing an additional dummy write to UBRRH, the baud rate is set correctly. The following is an example on how to set UBRR. UBRRH is updated first for upward compatibility with corrected devices.
ldi r17, HIGH(baud) ldi r16, LOW(baud) out UBRRH, r17 out UBRRL, r16 out UBRRH, r17 out UBRRH, r17 ; Added for upward compatibility ; Set new UBRRL, UBRRH incorrectly cleared ; Set new UBRRH ; Loads the baud rate counter with new (correct) value
1. Missing OverRun Flag and Fake Frame Error in USART When the USART has received three characters without any of them been read, the USART FIFO is full. If the USART detects the start bit of a fourth character, the Data OverRun (DOR) Flag will be set for the third character. However, if a read from the USART Data Register is performed just after the start bit of the fourth byte is received, a Frame Error is generated for character three. If the USART Data Register is read between the reception of the first data bit and the end of the fourth character, the Data OverRun Flag of character three will be lost. Problem Fix/Workaround The user should design the application to never completely fill the USART FIFO. If this is not possible, the user must use a high-level protocol to be able to detect if any characters were lost and request a retransmission if this happens. The following is not errata for ATmega323, all revisions. However, a proposal for solving problems regarding the JTAG instruction IDCODE is presented below. IDCODE masks data from TDI input The public but optional JTAG instruction IDCODE is not implemented correctly according to IEEE1149.1; a logic one is scanned into the shift register instead of the TDI input while shifting the Device ID Register. Hence, captured data from the preceding devices in the boundary scan chain are lost and replaced by all-ones, and data to succeeding devices are replaced by all-ones during Update-DR. If ATmega323 is the only device in the scan chain, the problem is not visible.
240
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Problem Fix / Workaround Select the Device ID Register of the ATmega323 (Either by issuing the IDCODE instruction or by entering the Test-Logic-Reset state of the TAP controller) to read out the contents of its Device ID Register and possibly data from succeeding devices of the scan chain. Note that data to succeeding devices cannot be entered during this scan, but data to preceding devices can. Issue the BYPASS instruction to the ATmega323 to select its Bypass Register while reading the Device ID Registers of preceding devices of the boundary scan chain. Never read data from succeeding devices in the boundary scan chain or upload data to the succeeding devices while the Device ID Register is selected for the ATmega323. Note that the IDCODE instruction is the default instruction selected by the Test-Logic-Reset state of the TAP-controller. Alternative Problem Fix / Workaround If the Device IDs of all devices in the boundary scan chain must be captured simultaneously (for instance if blind interrogation is used), the boundary scan chain can be connected in such way that the ATmega323 is the fist device in the chain. Update-DR will still not work for the succeeding devices in the boundary scan chain as long as IDCODE is present in the JTAG Instruction Register, but the Device ID registered cannot be uploaded in any case.
241
1457G-AVR-09/03
Datasheet Change Log for ATmega323
Changes from Rev. 1457F - 09/02 to Rev. 1457G - 09/03
This document contains a log on the changes made to the datasheet for ATmega323.
1. Removed "Preliminary" from the . 2. Updated "The Test Access Port - TAP" on page 158 regarding JTAGEN. 3. Updated description for the JTD bit on page 30. 4. Added extra information regarding the JTAGEN interface to "Fuse Bits" on page 187. 5. Updated some values in "Electrical Characteristics" on page 213. 5. Added a proposal for solving problems regarding the JTAG instruction IDCODE in "Errata for ATmega323 Rev. B" on page 239.
Changes from Rev. 1457E - 11/01 to Rev. 1457F - 09/02
1. Added watermark: "Not recommended for new designs. Use ATmega32". 2. Added "Errata for ATmega323 Rev. B" on page 239.
242
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Table of Contents
Features................................................................................................ 1 Pin Configurations............................................................................... 2 Overview ............................................................................................... 3
Block Diagram ...................................................................................................... 3 Pin Descriptions.................................................................................................... 4
Clock Options ...................................................................................... 6
Internal RC Oscillator............................................................................................ Crystal Oscillator................................................................................................... External Clock....................................................................................................... External RC Oscillator .......................................................................................... Timer Oscillator..................................................................................................... 6 6 7 7 7
Architectural Overview........................................................................ 8
The General Purpose Register File .................................................................... The ALU - Arithmetic Logic Unit......................................................................... The In-System Reprogrammable Flash Program Memory ................................. The SRAM Data Memory.................................................................................... The Program and Data Addressing Modes ........................................................ The EEPROM Data Memory .............................................................................. Memory Access Times and Instruction Execution Timing .................................. I/O Memory ......................................................................................................... Reset and Interrupt Handling.............................................................................. Sleep Modes....................................................................................................... 11 12 12 12 13 17 17 18 22 39
Calibrated Internal RC Oscillator ..................................................... 41 Timer/Counters .................................................................................. 43
Timer/Counter Prescalers................................................................................... 43 8-bit Timers/Counters Timer/Counter0 and Timer/Counter2 .............................. 45 16-bit Timer/Counter1......................................................................................... 54
Watchdog Timer................................................................................. 64 EEPROM Read/Write Access............................................................ 66
Preventing EEPROM Corruption ........................................................................ 68
Serial Peripheral Interface - SPI....................................................... 69
SS Pin Functionality............................................................................................ 70 Data Modes ........................................................................................................ 71
USART ................................................................................................ 74
Overview............................................................................................................. 74 ATmega323 USART Pin Specification ............................................................... 75
i
1457G-AVR-09/03
About Code Examples ........................................................................................ 75 AVR USART vs. AVR UART - Compatibility...................................................... 75
Clock Generation ............................................................................... 76
Frame Formats ................................................................................................... Parity Bit Calculation........................................................................................... USART Initialization............................................................................................ Data Transmission - The USART Transmitter ................................................... Data Reception - The USART Receiver ............................................................ Asynchronous Data Reception ........................................................................... Multi-processor Communication Mode ............................................................... Accessing UBRRH/UCSRC Registers................................................................ USART Register Description .............................................................................. Examples of Baud Rate Setting.......................................................................... 78 79 79 81 84 88 91 92 94 99
Two-wire Serial Interface (Byte Oriented) ..................................... 102
Two-wire Serial Interface Modes ...................................................................... Master Transmitter Mode.................................................................................. Master Receiver Mode...................................................................................... Slave Receiver Mode........................................................................................ Slave Transmitter Mode.................................................................................... Miscellaneous States........................................................................................ 107 108 108 109 110 110
The Analog Comparator.................................................................. 124
Analog Comparator Multiplexed Input .............................................................. 126
Analog to Digital Converter ............................................................ 127
Features............................................................................................................ Operation .......................................................................................................... Prescaling and Conversion Timing ................................................................... ADC Noise Canceler Function.......................................................................... Scanning Multiple Channels ............................................................................. ADC Noise Canceling Techniques ................................................................... ADC Characteristics - Preliminary Data........................................................... 127 128 129 131 135 135 136
I/O Ports............................................................................................ 137
Port A................................................................................................................ Port B................................................................................................................ Port C................................................................................................................ Port D................................................................................................................ 137 139 146 151
JTAG Interface and the On-chip Debug System ........................... 157
Features............................................................................................................ Overview........................................................................................................... The Test Access Port - TAP ............................................................................ Using the Boundary-Scan Chain ...................................................................... 157 157 158 161
ii
ATmega323(L)
1457G-AVR-09/03
ATmega323(L)
Using the On-chip Debug System .................................................................... 161 On-chip Debug Specific JTAG Instructions ...................................................... 162 Using the JTAG Programming Capabilities ...................................................... 163
IEEE 1149.1 (JTAG) Boundary-Scan .............................................. 164
Features............................................................................................................ System Overview.............................................................................................. Data Registers .................................................................................................. Boundary-Scan Specific JTAG Instructions...................................................... Boundary-Scan Chain....................................................................................... ATmega323 Boundary-Scan Order .................................................................. Boundary-Scan Description Language Files .................................................... 164 164 165 166 168 172 176
Memory Programming..................................................................... 177
Boot Loader Support......................................................................................... Entering the Boot Loader Program ................................................................... Capabilities of the Boot Loader......................................................................... Self-programming the Flash ............................................................................. Boot Loader Lock Bits....................................................................................... EEPROM Write Prevents Writing to SPMCR ................................................... Preventing Flash Corruption ............................................................................. Program and Data Memory Lock Bits............................................................... Parallel Programming ....................................................................................... Serial Downloading........................................................................................... 177 179 179 179 180 182 184 186 188 197
Programming via the JTAG Interface ............................................ 202
Programming specific JTAG instructions.......................................................... Data Registers .................................................................................................. Reset Register .................................................................................................. Programming Enable Register.......................................................................... Programming Command Register .................................................................... 202 203 203 203 204
Virtual Flash Page Load Register................................................... 208
Virtual Flash Page Read Register .................................................................... 209 Programming algorithm .................................................................................... 209
Electrical Characteristics................................................................ 213
Absolute Maximum Ratings*............................................................................. DC Characteristics............................................................................................ External Clock Drive Waveforms ...................................................................... External Clock Drive ......................................................................................... 213 213 215 215
Two-wire Serial Interface Characteristics ..................................... 216 ATmega323 Typical Characteristics - Preliminary Data .............. 218
iii
1457G-AVR-09/03
Register Summary ........................................................................... 231 Instruction Set Summary ................................................................ 233 Ordering Information ....................................................................... 236 Packaging Information .................................................................... 237
44A ................................................................................................................... 237 40P6 ................................................................................................................. 238
Errata for ATmega323 Rev. B ......................................................... 239 Datasheet Change Log for ATmega323......................................... 242
Changes from Rev. 1457F - 09/02 to Rev. 1457G - 09/03 ............................. 242 Changes from Rev. 1457E - 11/01 to Rev. 1457F - 09/02.............................. 242
Table of Contents ................................................................................. i
iv
ATmega323(L)
1457G-AVR-09/03
Atmel Corporation
2325 Orchard Parkway San Jose, CA 95131, USA Tel: 1(408) 441-0311 Fax: 1(408) 487-2600
Atmel Operations
Memory
2325 Orchard Parkway San Jose, CA 95131, USA Tel: 1(408) 441-0311 Fax: 1(408) 436-4314
RF/Automotive
Theresienstrasse 2 Postfach 3535 74025 Heilbronn, Germany Tel: (49) 71-31-67-0 Fax: (49) 71-31-67-2340 1150 East Cheyenne Mtn. Blvd. Colorado Springs, CO 80906, USA Tel: 1(719) 576-3300 Fax: 1(719) 540-1759
Regional Headquarters
Europe
Atmel Sarl Route des Arsenaux 41 Case Postale 80 CH-1705 Fribourg Switzerland Tel: (41) 26-426-5555 Fax: (41) 26-426-5500
Microcontrollers
2325 Orchard Parkway San Jose, CA 95131, USA Tel: 1(408) 441-0311 Fax: 1(408) 436-4314 La Chantrerie BP 70602 44306 Nantes Cedex 3, France Tel: (33) 2-40-18-18-18 Fax: (33) 2-40-18-19-60
Biometrics/Imaging/Hi-Rel MPU/ High Speed Converters/RF Datacom
Avenue de Rochepleine BP 123 38521 Saint-Egreve Cedex, France Tel: (33) 4-76-58-30-00 Fax: (33) 4-76-58-34-80
Asia
Room 1219 Chinachem Golden Plaza 77 Mody Road Tsimshatsui East Kowloon Hong Kong Tel: (852) 2721-9778 Fax: (852) 2722-1369
ASIC/ASSP/Smart Cards
Zone Industrielle 13106 Rousset Cedex, France Tel: (33) 4-42-53-60-00 Fax: (33) 4-42-53-60-01 1150 East Cheyenne Mtn. Blvd. Colorado Springs, CO 80906, USA Tel: 1(719) 576-3300 Fax: 1(719) 540-1759 Scottish Enterprise Technology Park Maxwell Building East Kilbride G75 0QR, Scotland Tel: (44) 1355-803-000 Fax: (44) 1355-242-743
Japan
9F, Tonetsu Shinkawa Bldg. 1-24-8 Shinkawa Chuo-ku, Tokyo 104-0033 Japan Tel: (81) 3-3523-3551 Fax: (81) 3-3523-7581
Literature Requests
www.atmel.com/literature
Disclaimer: Atmel Corporation makes no warranty for the use of its products, other than those expressly contained in the Company's standard warranty which is detailed in Atmel's Terms and Conditions located on the Company's web site. The Company assumes no responsibility for any errors which may appear in this document, reserves the right to change devices or specifications detailed herein at any time without notice, and does not make any commitment to update the information contained herein. No licenses to patents or other intellectual property of Atmel are granted by the Company in connection with the sale of Atmel products, expressly or by implication. Atmel's products are not authorized for use as critical components in life support devices or systems.
(c) Atmel Corporation 2003. All rights reserved. Atmel (R) and combinations thereof, AVR(R), and AVR Studio (R) are the registered trademarks of Atmel Corporation or its subsidiaries. Microsoft (R), Windows(R), Windows NT(R), and Windows XP (R) are the registered trademarks of Microsoft Corporation. Other terms and product names may be the trademarks of others
Printed on recycled paper.
1457G-AVR-09/03


▲Up To Search▲   

 
Price & Availability of ATMEGA323-8PC

All Rights Reserved © IC-ON-LINE 2003 - 2022  

[Add Bookmark] [Contact Us] [Link exchange] [Privacy policy]
Mirror Sites :  [www.datasheet.hk]   [www.maxim4u.com]  [www.ic-on-line.cn] [www.ic-on-line.com] [www.ic-on-line.net] [www.alldatasheet.com.cn] [www.gdcy.com]  [www.gdcy.net]


 . . . . .
  We use cookies to deliver the best possible web experience and assist with our advertising efforts. By continuing to use this site, you consent to the use of cookies. For more information on cookies, please take a look at our Privacy Policy. X